-
-
Notifications
You must be signed in to change notification settings - Fork 916
/
create.js
66 lines (53 loc) 路 1.46 KB
/
create.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
'use strict';
const extend = require('extend');
const is = require('@sindresorhus/is');
const asStream = require('./as-stream');
const asPromise = require('./as-promise');
const errors = require('./errors');
const normalizeArguments = require('./normalize-arguments');
const assignOptions = (defaults, options = {}) => {
const opts = extend(true, {}, defaults, options);
if (Reflect.has(options, 'headers')) {
for (const [key, value] of Object.entries(options.headers)) {
if (is.nullOrUndefined(value)) {
delete opts.headers[key];
continue;
}
}
}
return opts;
};
const create = (defaults = {}) => {
function got(url, options) {
try {
options = assignOptions(defaults, options);
const normalizedArgs = normalizeArguments(url, options);
if (normalizedArgs.stream) {
return asStream(normalizedArgs);
}
return asPromise(normalizedArgs);
} catch (error) {
return Promise.reject(error);
}
}
got.create = (options = {}) => create(assignOptions(defaults, options));
got.stream = (url, options) => {
options = assignOptions(defaults, options);
return asStream(normalizeArguments(url, options));
};
const methods = [
'get',
'post',
'put',
'patch',
'head',
'delete'
];
for (const method of methods) {
got[method] = (url, options) => got(url, {...options, method});
got.stream[method] = (url, options) => got.stream(url, {...options, method});
}
Object.assign(got, errors);
return got;
};
module.exports = create;