UNPKG

1.62 kBJavaScriptView Raw
1'use strict';
2
3const qs = require('qs');
4
5class Request {
6 constructor() {
7 this._queries = {};
8 this._headers = {};
9 this._timeout = undefined;
10 this._method = undefined;
11 this._baseUrl = undefined;
12 this._body;
13 }
14
15 addQuery(k, v) {
16 if (arguments.length === 0 || v === undefined) {
17 return this;
18 }
19
20 this._queries[k] = v;
21 return this;
22 }
23
24 addHeader(k, v) {
25 if (arguments.length === 0 || v === undefined) {
26 return this;
27 }
28
29 this._headers[k] = v;
30 return this;
31 }
32
33 body(content) {
34 this._body = content;
35 return this;
36 }
37
38 method(method) {
39 this._method = method;
40 return this;
41 }
42
43 baseUrl(baseUrl) {
44 this._baseUrl = baseUrl;
45 return this;
46 }
47
48 timeout(timeout) {
49 this._timeout = timeout;
50 return this;
51 }
52
53 getMethod() {
54 return this._method;
55 }
56
57 getTimeout() {
58 return this._timeout;
59 }
60
61 getUrl() {
62 if (this.hasQueries()) {
63 const delimiter = this.hasBaseQueries() ? '&' : '?';
64 return `${this._baseUrl}${delimiter}${qs.stringify(this._queries)}`;
65 }
66
67 return this._baseUrl;
68 }
69
70 getRequestKey() {
71 return `${this.getMethod()}:${this.getUrl()}`;
72 }
73
74 getHeaders() {
75 return this._headers;
76 }
77
78 getQueries() {
79 return this._queries;
80 }
81
82 hasQueries() {
83 return Object.keys(this._queries).length > 0;
84 }
85
86 hasBaseQueries() {
87 return this._baseUrl.indexOf('?') >= 0;
88 }
89
90 hasHeaders() {
91 return Object.keys(this._headers).length > 0;
92 }
93
94 getBody() {
95 return this._body;
96 }
97
98 static create() {
99 return new Request();
100 }
101}
102
103module.exports = Request;