forked from panva/node-openid-client
-
Notifications
You must be signed in to change notification settings - Fork 1
/
request.js
72 lines (58 loc) · 1.75 KB
/
request.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"use strict";
const request = require('request');
const got = require('got');
const PCancelable = require('p-cancelable');
const querystring = require('querystring');
const isPlainObj = require('is-plain-obj');
function mapGotOptions(gotOptions) {
let body = gotOptions.body;
const headers = {};
if (gotOptions.body && isPlainObj(gotOptions.body) && !gotOptions.json) {
body = querystring.stringify(gotOptions.body);
headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
return Object.assign({}, gotOptions, {
headers: Object.assign({}, gotOptions.headers, headers),
body: body || undefined,
qs: gotOptions.query,
});
}
/**
* A PCancelable wrapper around request that transforms `got`-like requests
* into `request` requests.
*
* @param {string} url the URL to call
* @param {object} options
* @returns {Promise}
*/
function req(url, gotOptions) {
return new PCancelable((onCancel, resolve, reject) => {
const requestOptions = mapGotOptions(gotOptions);
request(url, requestOptions, (error, response) => {
const limitStatusCode = requestOptions.followRedirect ? 299 : 399;
if (error) {
return reject(error);
}
const statusCode = response.statusCode;
if (statusCode !== 304 && (statusCode < 200 || statusCode > limitStatusCode)) {
const err = new got.HTTPError(response.statusCode, response.headers, requestOptions);
err.response = response;
return reject(err);
}
return resolve(response);
});
});
}
const helpers = [
'get',
'post',
'put',
'patch',
'head',
'delete',
];
helpers.forEach((el) => {
req[el] = (url, opts) => req(url, Object.assign({}, opts, { method: el }));
});
req.HTTPError = got.HTTPError;
module.exports = req;