1 | const { URL } = require('url');
|
2 | const fetch = require('node-fetch');
|
3 | const errorHandler = require('./error-handler');
|
4 |
|
5 | module.exports = function (baseUrl, defaultOptions) {
|
6 | return function (path, options, query) {
|
7 | const opts = Object.assign({}, defaultOptions, options);
|
8 |
|
9 | if (opts.json) {
|
10 | opts.body = JSON.stringify(opts.body);
|
11 | opts.headers = Object.assign({}, opts.headers, { 'Content-Type': 'application/json' });
|
12 | }
|
13 |
|
14 | const url = new URL(`${baseUrl}/${path}`);
|
15 |
|
16 | if (query)
|
17 | Object.keys(query).forEach(key => url.searchParams.append(key, query[key]));
|
18 |
|
19 | return new Promise((resolve, reject) => {
|
20 | let statusCode = 0;
|
21 |
|
22 | fetch(url, opts)
|
23 | .then(res => {
|
24 | statusCode = res.status;
|
25 |
|
26 | if (statusCode === 204) {
|
27 | resolve({});
|
28 | return;
|
29 | }
|
30 |
|
31 | return res;
|
32 | })
|
33 | .then(res => res.json())
|
34 | .then(res => errorHandler(res, reject, statusCode))
|
35 | .then(res => {
|
36 | if (res.data && !Array.isArray(res.data))
|
37 | res.data = [];
|
38 |
|
39 | resolve(res)
|
40 | })
|
41 | .catch(err => errorHandler(err, reject, statusCode));
|
42 | });
|
43 | }
|
44 | };
|