1 | 'use strict';
|
2 |
|
3 | const _ = require('lodash');
|
4 |
|
5 | const Request = require('./request');
|
6 | const Response = require('./response');
|
7 | const packageInfo = require('../package');
|
8 |
|
9 | const RETRIES = 0;
|
10 | const RETRY_DELAY = 100;
|
11 | const USER_AGENT = `${packageInfo.name}/${packageInfo.version}`;
|
12 |
|
13 | class 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 |
|
51 | module.exports = Context;
|