Files

44 lines
1.4 KiB
JavaScript
Raw Permalink Normal View History

2018-05-18 15:15:14 +08:00
const logger = require('./logger');
2019-09-18 17:45:21 +08:00
const config = require('@/config').value;
2019-02-28 21:51:24 +08:00
const got = require('got');
2018-05-18 15:15:14 +08:00
2019-02-28 21:51:24 +08:00
const custom = got.extend({
retry: {
limit: config.requestRetry,
statusCodes: [400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 421, 422, 423, 424, 426, 428, 429, 431, 451, 500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511, 521, 522, 524],
},
2019-02-28 21:51:24 +08:00
hooks: {
beforeRetry: [
(options, err, count) => {
logger.error(`Request ${options.url} fail, retry attempt #${count}: ${err}`);
options.retryCount = count;
2019-02-28 21:51:24 +08:00
},
],
afterResponse: [
(response) => {
2019-06-04 11:13:54 +08:00
try {
response.data = JSON.parse(response.body);
} catch (e) {
2019-02-28 21:51:24 +08:00
response.data = response.body;
}
2019-03-10 00:19:54 +08:00
response.status = response.statusCode;
2019-02-28 21:51:24 +08:00
return response;
},
],
2019-06-04 15:10:27 +08:00
init: [
2019-04-18 00:20:39 +08:00
(options) => {
2019-06-04 15:10:27 +08:00
// compatible with axios api
2020-05-06 19:47:51 +08:00
if (options && options.data) {
2019-06-04 18:28:06 +08:00
options.body = options.body || options.data;
2019-06-04 15:10:27 +08:00
}
2019-04-18 00:20:39 +08:00
},
],
2019-02-28 21:51:24 +08:00
},
headers: {
'user-agent': config.ua,
2018-05-18 15:15:14 +08:00
},
2021-02-01 20:06:49 +08:00
timeout: config.requestTimeout,
2018-05-18 15:15:14 +08:00
});
2019-06-04 11:54:20 +08:00
custom.all = (list) => Promise.all(list);
2018-05-18 15:15:14 +08:00
2019-02-28 21:51:24 +08:00
module.exports = custom;