create.js
2.06 KB
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
73
74
75
76
77
78
79
'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('./utils/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);
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 => {
let mutableDefaults;
if (options && Reflect.has(options, 'mutableDefaults')) {
mutableDefaults = options.mutableDefaults;
delete options.mutableDefaults;
} else {
mutableDefaults = defaults.mutableDefaults;
}
return create({
options: merge.options(defaults.options, options),
handler: defaults.handler,
mutableDefaults
});
};
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: defaults.mutableDefaults ? defaults : deepFreeze(defaults),
writable: defaults.mutableDefaults,
configurable: defaults.mutableDefaults,
enumerable: true
});
return got;
};
module.exports = create;