UNPKG

2.07 kBJavaScriptView Raw
1const _ = {
2 cloneDeep: require('lodash.clonedeep'),
3 isArray: require('lodash.isarray'),
4 mergeWith: require('lodash.mergewith'),
5};
6const rp = require('request-promise');
7const URI = require('urijs');
8
9class Request {
10 constructor(options) {
11 this.options = {
12 timeout: 1000,
13 };
14 if (options) {
15 this.addOptions(options);
16 }
17 }
18
19 addOptions(options) {
20 if (Array.isArray(options)) {
21 options.forEach(options => this.addOptions(options));
22 return this;
23 }
24 if (options.toRequestOptions) {
25 this.addOptions(options.toRequestOptions(this.options));
26 return this;
27 }
28 _.mergeWith(this.options, options, (to, from) => {
29 if (_.isArray(from)) {
30 if (!to) {
31 to = [];
32 }
33 return to.concat(from);
34 }
35 });
36 return this;
37 }
38
39 getOptions() {
40 const options = _.cloneDeep(this.options);
41 if (typeof options.url === 'object') {
42 const url = new URI(options.url);
43 if (typeof options.url.query === 'object') {
44 url.query(options.url.query);
45 }
46 if (typeof options.url.search === 'object') {
47 url.search(options.url.search);
48 }
49 options.url = url.toString();
50 }
51 return options;
52 }
53
54 send(path, options) {
55 if (typeof path === 'object') {
56 options = path;
57 path = undefined;
58 }
59 if (path) {
60 this.addOptions({ url: { path } });
61 }
62 if (options) {
63 this.addOptions(options);
64 }
65 options = this.getOptions();
66 if (typeof options.body === 'object') {
67 options.json = true;
68 }
69 return rp(options);
70 }
71
72 delete(path, options) {
73 this.addOptions({ method: 'delete' });
74 return this.send(path, options);
75 }
76
77 get(path, options) {
78 this.addOptions({ method: 'get' });
79 return this.send(path, options);
80 }
81
82 post(path, options) {
83 this.addOptions({ method: 'post' });
84 return this.send(path, options);
85 }
86
87 put(path, options) {
88 this.addOptions({ method: 'put' });
89 return this.send(path, options);
90 }
91}
92
93module.exports = Request;