@k03mad/request 2.1.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/app/lib/curl.js +0 -3
- package/app/lib/queue.js +3 -11
- package/app/lib/request.js +32 -33
- package/package.json +2 -2
package/app/lib/curl.js
CHANGED
|
@@ -4,7 +4,6 @@ import prettyBytes from 'pretty-bytes';
|
|
|
4
4
|
const {bgWhite, black, blue, dim, green, magenta, red, white, yellow} = chalk;
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
|
-
* Сформировать curl-строку из опций got
|
|
8
7
|
* @param {string} url
|
|
9
8
|
* @param {object} [opts]
|
|
10
9
|
* @param {string} [opts.method]
|
|
@@ -25,12 +24,10 @@ export default (url, {
|
|
|
25
24
|
}, res) => {
|
|
26
25
|
const msg = [];
|
|
27
26
|
|
|
28
|
-
// если третий параметр — объект ошибки, то все необходимое на уровень ниже, в ключе response
|
|
29
27
|
if (res?.response) {
|
|
30
28
|
res = res.response;
|
|
31
29
|
}
|
|
32
30
|
|
|
33
|
-
// 200 [800 ms] [3.15 kB]
|
|
34
31
|
if (res?.statusCode) {
|
|
35
32
|
msg.push(bgWhite(black(res.statusCode)));
|
|
36
33
|
}
|
package/app/lib/queue.js
CHANGED
|
@@ -6,9 +6,9 @@ const debug = _debug('mad:queue');
|
|
|
6
6
|
// const rps = num => ({intervalCap: num, interval: 1000});
|
|
7
7
|
const concurrency = num => ({concurrency: num});
|
|
8
8
|
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
9
|
+
// first level — host
|
|
10
|
+
// second level — method
|
|
11
|
+
// third level — p-queue options
|
|
12
12
|
const requestQueue = {
|
|
13
13
|
'*': {
|
|
14
14
|
'*': concurrency(3),
|
|
@@ -16,7 +16,6 @@ const requestQueue = {
|
|
|
16
16
|
};
|
|
17
17
|
|
|
18
18
|
/**
|
|
19
|
-
* Поставить логирование и вернуть очередь
|
|
20
19
|
* @param {string} host
|
|
21
20
|
* @param {string} method
|
|
22
21
|
* @param {object} opts
|
|
@@ -44,20 +43,16 @@ const getLoggedQueue = (host, method, opts) => {
|
|
|
44
43
|
};
|
|
45
44
|
|
|
46
45
|
/**
|
|
47
|
-
* Получить очередь по хосту и методу
|
|
48
46
|
* @param {string} host
|
|
49
47
|
* @param {string} method
|
|
50
48
|
* @returns {object}
|
|
51
49
|
*/
|
|
52
50
|
export default (host, method = 'GET') => {
|
|
53
|
-
// проверка на предустановленные настройки очереди для хоста и метода
|
|
54
51
|
for (const elem of [method, '*']) {
|
|
55
|
-
// очередь уже проинициализирована
|
|
56
52
|
if (requestQueue[host]?.[elem]?._events) {
|
|
57
53
|
return requestQueue[host][elem];
|
|
58
54
|
}
|
|
59
55
|
|
|
60
|
-
// очередь нужно проинициализировать
|
|
61
56
|
if (requestQueue[host]?.[elem]) {
|
|
62
57
|
const opts = requestQueue[host][elem];
|
|
63
58
|
requestQueue[host][elem] = new PQueue(opts);
|
|
@@ -65,21 +60,18 @@ export default (host, method = 'GET') => {
|
|
|
65
60
|
}
|
|
66
61
|
}
|
|
67
62
|
|
|
68
|
-
// инициализация очереди для хоста без текущего метода в предустановках
|
|
69
63
|
if (requestQueue[host]) {
|
|
70
64
|
const opts = requestQueue['*']['*'];
|
|
71
65
|
requestQueue[host]['*'] = new PQueue(opts);
|
|
72
66
|
return getLoggedQueue(host, '*', opts);
|
|
73
67
|
}
|
|
74
68
|
|
|
75
|
-
// инициализация очереди для хоста с методом из предустановок для всех очередей
|
|
76
69
|
if (requestQueue['*'][method]) {
|
|
77
70
|
const opts = requestQueue['*'][method];
|
|
78
71
|
requestQueue[host] = {[method]: new PQueue(opts)};
|
|
79
72
|
return getLoggedQueue(host, method, opts);
|
|
80
73
|
}
|
|
81
74
|
|
|
82
|
-
// нет ни хоста не метода в предустановках
|
|
83
75
|
const opts = requestQueue['*']['*'];
|
|
84
76
|
requestQueue[host] = {'*': new PQueue(opts)};
|
|
85
77
|
return getLoggedQueue(host, '*', opts);
|
package/app/lib/request.js
CHANGED
|
@@ -8,21 +8,37 @@ import getQueue from './queue.js';
|
|
|
8
8
|
const {blue, cyan, dim, green, red, yellow} = chalk;
|
|
9
9
|
const debug = _debug('mad:request');
|
|
10
10
|
|
|
11
|
-
const
|
|
11
|
+
const gotCache = new Map();
|
|
12
|
+
|
|
13
|
+
const cacheGotResponseKeys = [
|
|
14
|
+
'body',
|
|
15
|
+
'headers',
|
|
16
|
+
'method',
|
|
17
|
+
'statusCode',
|
|
18
|
+
'statusMessage',
|
|
19
|
+
'timings',
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
const gotDefaultOpts = got.extend({
|
|
12
23
|
dnsCache: true,
|
|
13
24
|
timeout: {request: 15_000},
|
|
14
|
-
headers: {'user-agent': 'curl/
|
|
25
|
+
headers: {'user-agent': 'curl/7.81.0'},
|
|
15
26
|
});
|
|
16
27
|
|
|
28
|
+
const cacheDebug = msgArr => {
|
|
29
|
+
if (process.env.DEBUG) {
|
|
30
|
+
debug(msgArr.join(' :: '));
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
|
|
17
34
|
/**
|
|
18
|
-
* Отправить запрос
|
|
19
35
|
* @param {string} url
|
|
20
36
|
* @param {object} opts
|
|
21
37
|
* @returns {object}
|
|
22
38
|
*/
|
|
23
39
|
const sendRequest = async (url, opts) => {
|
|
24
40
|
try {
|
|
25
|
-
const response = await
|
|
41
|
+
const response = await gotDefaultOpts(url, opts);
|
|
26
42
|
|
|
27
43
|
if (!opts.responseType) {
|
|
28
44
|
try {
|
|
@@ -65,21 +81,12 @@ const sendRequest = async (url, opts) => {
|
|
|
65
81
|
}
|
|
66
82
|
};
|
|
67
83
|
|
|
68
|
-
export const cache = new Map();
|
|
69
|
-
|
|
70
84
|
/**
|
|
71
|
-
* Отправить запрос c выбором использования очереди
|
|
72
85
|
* @param {string} url
|
|
73
86
|
* @param {object} [opts]
|
|
74
|
-
* @param {object} [params]
|
|
75
|
-
* @param {boolean} [params.skipQueue]
|
|
76
87
|
* @returns {Promise<object>}
|
|
77
88
|
*/
|
|
78
|
-
export const request = (url, opts = {}
|
|
79
|
-
if (skipQueue) {
|
|
80
|
-
return sendRequest(url, opts);
|
|
81
|
-
}
|
|
82
|
-
|
|
89
|
+
export const request = (url, opts = {}) => {
|
|
83
90
|
const queue = getQueue(new URL(url).host, opts.method);
|
|
84
91
|
return queue.add(() => sendRequest(url, opts));
|
|
85
92
|
};
|
|
@@ -96,39 +103,31 @@ export const requestCache = (url, opts = {}, {cacheBy, expire = 43_200} = {}) =>
|
|
|
96
103
|
const queue = getQueue(new URL(url).host, opts.method);
|
|
97
104
|
|
|
98
105
|
return queue.add(async () => {
|
|
99
|
-
const cacheGotResponseKeys = [
|
|
100
|
-
'body',
|
|
101
|
-
'headers',
|
|
102
|
-
'method',
|
|
103
|
-
'statusCode',
|
|
104
|
-
'statusMessage',
|
|
105
|
-
'timings',
|
|
106
|
-
];
|
|
107
|
-
|
|
108
106
|
const cacheKey = `${url}::${JSON.stringify(cacheBy || opts)}`;
|
|
109
|
-
const
|
|
107
|
+
const urlLog = `${blue(url)}\n${dim(cacheKey)}`;
|
|
110
108
|
|
|
111
109
|
try {
|
|
112
|
-
if (
|
|
113
|
-
const {cachedResponse, date} =
|
|
110
|
+
if (gotCache.has(cacheKey)) {
|
|
111
|
+
const {cachedResponse, date} = gotCache.get(cacheKey);
|
|
114
112
|
|
|
115
113
|
const measurement = 'seconds';
|
|
116
114
|
const currentDiff = Math.round((Date.now() - date) / 1000);
|
|
115
|
+
const diffLog = `${currentDiff}/${expire} ${measurement} left`;
|
|
117
116
|
|
|
118
117
|
if (currentDiff < expire) {
|
|
119
|
-
|
|
118
|
+
cacheDebug([green('FROM CACHE'), diffLog, urlLog]);
|
|
120
119
|
return {cacheKey, ...cachedResponse};
|
|
121
120
|
}
|
|
122
121
|
|
|
123
|
-
|
|
122
|
+
cacheDebug([yellow('CACHE EXPIRED'), diffLog, urlLog]);
|
|
124
123
|
} else {
|
|
125
|
-
|
|
124
|
+
cacheDebug([blue('CACHE NOT FOUND'), urlLog]);
|
|
126
125
|
}
|
|
127
126
|
} catch (err) {
|
|
128
|
-
|
|
127
|
+
cacheDebug([red('CACHE ERROR'), dim(err), urlLog]);
|
|
129
128
|
}
|
|
130
129
|
|
|
131
|
-
const res = await
|
|
130
|
+
const res = await sendRequest(url, opts);
|
|
132
131
|
|
|
133
132
|
const cachedResponse = {};
|
|
134
133
|
|
|
@@ -136,8 +135,8 @@ export const requestCache = (url, opts = {}, {cacheBy, expire = 43_200} = {}) =>
|
|
|
136
135
|
cachedResponse[key] = res[key];
|
|
137
136
|
});
|
|
138
137
|
|
|
139
|
-
|
|
140
|
-
|
|
138
|
+
gotCache.set(cacheKey, {date: Date.now(), cachedResponse});
|
|
139
|
+
cacheDebug([cyan('CACHE SAVED'), urlLog]);
|
|
141
140
|
|
|
142
141
|
return res;
|
|
143
142
|
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@k03mad/request",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"description": "Request library",
|
|
5
5
|
"maintainers": [
|
|
6
6
|
"Kirill Molchanov <k03.mad@gmail.com"
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
"pretty-bytes": "6.1.1"
|
|
21
21
|
},
|
|
22
22
|
"devDependencies": {
|
|
23
|
-
"@k03mad/eslint-config": "12.0.
|
|
23
|
+
"@k03mad/eslint-config": "12.0.6",
|
|
24
24
|
"@microsoft/eslint-formatter-sarif": "3.0.0",
|
|
25
25
|
"eslint": "8.46.0",
|
|
26
26
|
"eslint-plugin-import": "2.28.0",
|