-
-
Notifications
You must be signed in to change notification settings - Fork 916
/
create.js
67 lines (56 loc) 路 1.73 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
67
'use strict';
const errors = require('./errors');
const asStream = require('./as-stream');
const asPromise = require('./as-promise');
const normalizeArguments = require('./normalize-arguments');
const merge = require('./merge');
const deepFreeze = require('./deep-freeze');
const getPromiseOrStream = options => options.stream ? asStream(options) : asPromise(options);
const aliases = [
'get',
'post',
'put',
'patch',
'head',
'delete'
];
const create = defaults => {
defaults = merge({}, defaults);
defaults.options = normalizeArguments.preNormalize(defaults.options);
if (!defaults.handler) {
// This can't be getPromiseOrStream, because when merging
// the chain would stop at this point and no further handlers would be called.
defaults.handler = (options, next) => next(options);
}
function got(url, options) {
try {
return defaults.handler(normalizeArguments(url, options, defaults), getPromiseOrStream);
} catch (error) {
if (options && options.stream) {
throw error;
} else {
return Promise.reject(error);
}
}
}
got.create = create;
got.extend = options => create({
options: merge.options(defaults.options, options),
handler: defaults.handler
});
got.mergeInstances = (...args) => create(merge.instances(args));
got.stream = (url, options) => got(url, {...options, stream: true});
for (const method of aliases) {
got[method] = (url, options) => got(url, {...options, method});
got.stream[method] = (url, options) => got.stream(url, {...options, method});
}
Object.assign(got, {...errors, mergeOptions: merge.options});
Object.defineProperty(got, 'defaults', {
value: deepFreeze(defaults),
writable: false,
enumerable: true,
configurable: true
});
return got;
};
module.exports = create;