UNPKG

2.48 kBJavaScriptView Raw
1'use strict';
2
3const _ = require('lodash');
4
5const HttpTransportClient = require('./client');
6
7function validatePlugin(plugin) {
8 if (typeof plugin !== 'function') throw new TypeError('Plugin is not a function');
9}
10
11/** @class */
12class HttpTransportBuilder {
13 /**
14 * Configures HttpTransport client
15 * @param {Transport} transport - Transport instance.
16 */
17 constructor(transport) {
18 this._transport = transport;
19 this._defaults = {
20 plugins: []
21 };
22 }
23
24 /**
25 * Sets a default user agent
26 *
27 * @param {string} agent - user agent
28 * @return a HttpTransportBuilder instance
29 * @example
30 * const httpTransport = require('@bbc/http-transport');
31 *
32 * const builder = httpTransport.createBuilder();
33 * builder.userAgent('some-user-agent');
34 */
35 userAgent(userAgent) {
36 _.set(this._defaults, 'ctx.userAgent', userAgent);
37 return this;
38 }
39
40 /**
41 * Set the default number of retries
42 *
43 * @param {integer} retries - number of retry attempts
44 * @return a HttpTransportBuilder instance
45 * @example
46 * const httpTransport = require('@bbc/http-transport');
47 *
48 * const builder = httpTransport.createBuilder();
49 * builder.retries(5);
50 */
51 retries(retries) {
52 _.set(this._defaults, 'ctx.retries', retries);
53 return this;
54 }
55
56 /**
57 * default time delay between retries
58 *
59 * @param {integer} delay - delay time in ms
60 * @return a HttpTransportBuilder instance
61 * @example
62 * const httpTransport = require('@bbc/http-transport');
63 *
64 * const builder = httpTransport.createBuilder();
65 * builder.retryDelay(1000);
66 */
67 retryDelay(delay) {
68 _.set(this._defaults, 'ctx.retryDelay', delay);
69 return this;
70 }
71
72 /**
73 * Registers a global plugin, which is used for all requests
74 *
75 * @param {function} fn - a global plugin
76 * @return a HttpTransportBuilder instance
77 * @example
78 * const toError = require('@bbc/http-transport-errors');
79 * const httpTransport = require('@bbc/http-transport');
80 *
81 * const client = httpTransport.createClient();
82 * client.useGlobal(toError(404));
83 */
84 use(fn) {
85 validatePlugin(fn);
86 this._defaults.plugins.push(fn);
87 return this;
88 }
89
90 /**
91 * Instantiates a HttpTransport
92 *
93 * @return a HttpTransport instance
94 * @example
95 *
96 * const client = httpTransport.createClient();
97 */
98 createClient() {
99 return new HttpTransportClient(this._transport, this._defaults);
100 }
101}
102
103module.exports = HttpTransportBuilder;