UNPKG

1.19 kBJavaScriptView Raw
1'use strict';
2
3const _ = require('lodash');
4
5const Request = require('./request');
6const Response = require('./response');
7const packageInfo = require('../package');
8
9const RETRIES = 0;
10const RETRY_DELAY = 100;
11const USER_AGENT = `${packageInfo.name}/${packageInfo.version}`;
12
13class Context {
14 constructor(defaults) {
15 this.retries = 0;
16 this._retryAttempts = [];
17 this.plugins = [];
18 this.req = Request.create();
19 this.res = Response.create();
20 if (defaults) this._applyDefaults(defaults);
21 }
22
23 get retryAttempts() {
24 if (_.isUndefined(this._retryAttempts)) return [];
25 return this._retryAttempts;
26 }
27
28 set retryAttempts(retryAttempts) {
29 if (!Array.isArray(retryAttempts)) {
30 retryAttempts = [];
31 }
32 this._retryAttempts = retryAttempts;
33 }
34
35 addPlugin(plugin) {
36 this.plugins.push(plugin);
37 return this;
38 }
39
40 _applyDefaults(defaults) {
41 this.userAgent = _.get(defaults, 'ctx.userAgent', USER_AGENT);
42 this.retries = _.get(defaults, 'ctx.retries', RETRIES);
43 this.retryDelay = _.get(defaults, 'ctx.retryDelay', RETRY_DELAY);
44 }
45
46 static create(defaults) {
47 return new Context(defaults);
48 }
49}
50
51module.exports = Context;