@k03mad/request 1.0.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/.editorconfig ADDED
@@ -0,0 +1,12 @@
1
+ root = true
2
+
3
+ [*]
4
+ charset = utf-8
5
+ end_of_line = lf
6
+ indent_size = 4
7
+ indent_style = space
8
+ insert_final_newline = true
9
+ trim_trailing_whitespace = true
10
+
11
+ [*.json]
12
+ indent_size = 2
package/.eslintrc.json ADDED
@@ -0,0 +1,3 @@
1
+ {
2
+ "extends": "@k03mad"
3
+ }
@@ -0,0 +1,6 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: "npm"
4
+ directory: "/"
5
+ schedule:
6
+ interval: "monthly"
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env sh
2
+ . "$(dirname -- "$0")/_/husky.sh"
3
+
4
+ npm run lint
package/.nvmrc ADDED
@@ -0,0 +1 @@
1
+ 20
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Kirill Molchanov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ Adds queues and logging to the `Got` library
package/app/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from './lib/request.js';
@@ -0,0 +1,89 @@
1
+ import chalk from 'chalk';
2
+ import prettyBytes from 'pretty-bytes';
3
+
4
+ const {bgWhite, black, blue, dim, green, magenta, red, white, yellow} = chalk;
5
+
6
+ /**
7
+ * Сформировать curl-строку из опций got
8
+ * @param {string} url
9
+ * @param {object} [opts]
10
+ * @param {string} [opts.method]
11
+ * @param {object} [opts.headers]
12
+ * @param {string} [opts.body]
13
+ * @param {object} [opts.json]
14
+ * @param {object} [opts.form]
15
+ * @param {object} [opts.searchParams]
16
+ * @param {string} [opts.username]
17
+ * @param {string} [opts.password]
18
+ * @param {object} res
19
+ * @returns {string}
20
+ */
21
+ export default (url, {
22
+ body, form,
23
+ headers = {}, json, method = 'GET', password,
24
+ searchParams, username,
25
+ }, res) => {
26
+ const msg = [];
27
+
28
+ // если третий параметр — объект ошибки, то все необходимое на уровень ниже, в ключе response
29
+ if (res?.response) {
30
+ res = res.response;
31
+ }
32
+
33
+ // 200 [800 ms] [3.15 kB]
34
+ if (res?.statusCode) {
35
+ msg.push(bgWhite(black(res.statusCode)));
36
+ }
37
+
38
+ if (res?.timings) {
39
+ msg.push(`[${res.timings.phases.total} ms]`);
40
+ }
41
+
42
+ if (res?.headers?.['content-length']) {
43
+ msg.push(`[${prettyBytes(Number(res.headers['content-length']))}]`);
44
+ }
45
+
46
+ if (searchParams) {
47
+ url += `?${new URLSearchParams(searchParams).toString()}`;
48
+ }
49
+
50
+ msg.push(white('curl -v -X'), green(method));
51
+
52
+ if (username && password) {
53
+ msg.push(dim(red(`-u ${username}:${password}`)));
54
+ }
55
+
56
+ msg.push(blue(url));
57
+
58
+ let bodyParams;
59
+
60
+ if (json) {
61
+ headers['content-type'] = 'application/json';
62
+ bodyParams = `-d '${JSON.stringify(json)}'`;
63
+ } else if (form) {
64
+ headers['content-type'] = 'application/x-www-form-urlencoded';
65
+ bodyParams = `-d '${new URLSearchParams(form).toString()}'`;
66
+ } else if (body) {
67
+ bodyParams = `-d '${body}'`;
68
+ }
69
+
70
+ const headersParams = Object.entries(headers);
71
+
72
+ if (headersParams.length > 0) {
73
+ msg.push(dim(magenta(headersParams.map(([key, value]) => `-H "${key}: ${value}"`).join(' '))));
74
+ }
75
+
76
+ if (bodyParams) {
77
+ msg.push(dim(yellow(bodyParams)));
78
+ }
79
+
80
+ if (res) {
81
+ const message = JSON.stringify(res.body || res.message);
82
+
83
+ if (message?.length < 1000) {
84
+ msg.push(`\n${dim(green(message))}`);
85
+ }
86
+ }
87
+
88
+ return msg.join(' ');
89
+ };
@@ -0,0 +1,86 @@
1
+ import _debug from 'debug';
2
+ import PQueue from 'p-queue';
3
+
4
+ const debug = _debug('mad:queue');
5
+
6
+ // const rps = num => ({intervalCap: num, interval: 1000});
7
+ const concurrency = num => ({concurrency: num});
8
+
9
+ // первый уровень — хост (* — любой, кроме уже перечисленных)
10
+ // второй уровень — метод (* — любой, кроме уже перечисленных)
11
+ // третий уровень — настройки очереди из p-queue
12
+ const requestQueue = {
13
+ '*': {
14
+ '*': concurrency(3),
15
+ },
16
+ };
17
+
18
+ /**
19
+ * Поставить логирование и вернуть очередь
20
+ * @param {string} host
21
+ * @param {string} method
22
+ * @param {object} opts
23
+ * @returns {object}
24
+ */
25
+ const getLoggedQueue = (host, method, opts) => {
26
+ const queue = requestQueue[host][method];
27
+
28
+ queue.on('active', () => {
29
+ const {pending, size} = queue;
30
+ const {concurrency: concurrent, interval, intervalCap} = opts;
31
+
32
+ const parallel = concurrent
33
+ ? `${concurrent} concurrent`
34
+ : `${intervalCap} rp ${interval} ms`;
35
+
36
+ const logMessage = `[${
37
+ method === '*' ? '' : `${method}: `
38
+ }${host}] ${parallel} | queue: ${size} | running: ${pending}`;
39
+
40
+ debug(logMessage);
41
+ });
42
+
43
+ return queue;
44
+ };
45
+
46
+ /**
47
+ * Получить очередь по хосту и методу
48
+ * @param {string} host
49
+ * @param {string} method
50
+ * @returns {object}
51
+ */
52
+ export default (host, method = 'GET') => {
53
+ // проверка на предустановленные настройки очереди для хоста и метода
54
+ for (const elem of [method, '*']) {
55
+ // очередь уже проинициализирована
56
+ if (requestQueue[host]?.[elem]?._events) {
57
+ return requestQueue[host][elem];
58
+ }
59
+
60
+ // очередь нужно проинициализировать
61
+ if (requestQueue[host]?.[elem]) {
62
+ const opts = requestQueue[host][elem];
63
+ requestQueue[host][elem] = new PQueue(opts);
64
+ return getLoggedQueue(host, elem, opts);
65
+ }
66
+ }
67
+
68
+ // инициализация очереди для хоста без текущего метода в предустановках
69
+ if (requestQueue[host]) {
70
+ const opts = requestQueue['*']['*'];
71
+ requestQueue[host]['*'] = new PQueue(opts);
72
+ return getLoggedQueue(host, '*', opts);
73
+ }
74
+
75
+ // инициализация очереди для хоста с методом из предустановок для всех очередей
76
+ if (requestQueue['*'][method]) {
77
+ const opts = requestQueue['*'][method];
78
+ requestQueue[host] = {[method]: new PQueue(opts)};
79
+ return getLoggedQueue(host, method, opts);
80
+ }
81
+
82
+ // нет ни хоста не метода в предустановках
83
+ const opts = requestQueue['*']['*'];
84
+ requestQueue[host] = {'*': new PQueue(opts)};
85
+ return getLoggedQueue(host, '*', opts);
86
+ };
@@ -0,0 +1,136 @@
1
+ import chalk from 'chalk';
2
+ import _debug from 'debug';
3
+ import got from 'got';
4
+
5
+ import getCurl from './curl.js';
6
+ import getQueue from './queue.js';
7
+
8
+ const {blue, cyan, dim, green, red, yellow} = chalk;
9
+ const debug = _debug('mad:request');
10
+
11
+ /**
12
+ * @param {object} opts
13
+ * @returns {object}
14
+ */
15
+ const prepareRequestOpts = (opts = {}) => {
16
+ const UA = 'curl/8.1.2';
17
+
18
+ const preparedOpts = {
19
+ timeout: {request: 15_000},
20
+ ...opts,
21
+ };
22
+
23
+ if (!preparedOpts.headers) {
24
+ preparedOpts.headers = {'user-agent': UA};
25
+ } else if (!preparedOpts.headers['user-agent']) {
26
+ preparedOpts.headers['user-agent'] = UA;
27
+ }
28
+
29
+ return preparedOpts;
30
+ };
31
+
32
+ /**
33
+ * Отправить запрос
34
+ * @param {string} url
35
+ * @param {object} opts
36
+ * @returns {object}
37
+ */
38
+ const sendRequest = async (url, opts) => {
39
+ const preparedOpts = prepareRequestOpts(opts);
40
+
41
+ try {
42
+ const response = await got(url, preparedOpts);
43
+
44
+ if (!preparedOpts.responseType) {
45
+ try {
46
+ response.body = JSON.parse(response.body);
47
+ } catch {}
48
+ }
49
+
50
+ debug(getCurl(url, preparedOpts, response));
51
+ return response;
52
+ } catch (err) {
53
+ debug(getCurl(url, preparedOpts, err));
54
+ throw err;
55
+ }
56
+ };
57
+
58
+ export const cache = new Map();
59
+
60
+ /**
61
+ * Отправить запрос c выбором использования очереди
62
+ * @param {string} url
63
+ * @param {object} [opts]
64
+ * @param {object} [params]
65
+ * @param {boolean} [params.skipQueue]
66
+ * @returns {Promise<object>}
67
+ */
68
+ export const request = (url, opts = {}, {skipQueue} = {}) => {
69
+ if (skipQueue) {
70
+ return sendRequest(url, opts);
71
+ }
72
+
73
+ const queue = getQueue(new URL(url).host, opts.method);
74
+ return queue.add(() => sendRequest(url, opts));
75
+ };
76
+
77
+ /**
78
+ * @param {string} url
79
+ * @param {object} [opts]
80
+ * @param {object} [params]
81
+ * @param {number} [params.expire] seconds
82
+ * @param {object} [params.cacheBy]
83
+ * @returns {Promise<object>}
84
+ */
85
+ export const requestCache = (url, opts = {}, {cacheBy, expire = 43_200} = {}) => {
86
+ const queue = getQueue(new URL(url).host, opts.method);
87
+
88
+ return queue.add(async () => {
89
+ const preparedOpts = prepareRequestOpts(opts);
90
+
91
+ const cacheGotResponseKeys = [
92
+ 'body',
93
+ 'headers',
94
+ 'method',
95
+ 'statusCode',
96
+ 'statusMessage',
97
+ 'timings',
98
+ ];
99
+
100
+ const cacheKey = `${url}::${JSON.stringify(cacheBy || preparedOpts)}`;
101
+ const log = `${blue(url)}\n${dim(cacheKey)}`;
102
+
103
+ try {
104
+ if (cache.has(cacheKey)) {
105
+ const {cachedResponse, date} = cache.get(cacheKey);
106
+
107
+ const measurement = 'seconds';
108
+ const currentDiff = (Date.now() - date) * 1000;
109
+
110
+ if (currentDiff < expire) {
111
+ debug(`${green('FROM CACHE')} :: ${currentDiff}/${expire} ${measurement} left :: ${log}`);
112
+ return {cacheKey, ...cachedResponse};
113
+ }
114
+
115
+ debug(`${red('CACHE EXPIRED')} :: ${currentDiff}/${expire} ${measurement} left :: ${log}`);
116
+ } else {
117
+ debug(`${yellow('CACHE NOT FOUND')} :: ${log}`);
118
+ }
119
+ } catch (err) {
120
+ debug(`${red('CACHE ERROR')} :: ${dim(err)} :: ${log}`);
121
+ }
122
+
123
+ const res = await request(url, preparedOpts, {skipQueue: true});
124
+
125
+ const cachedResponse = {};
126
+
127
+ cacheGotResponseKeys.forEach(key => {
128
+ cachedResponse[key] = res[key];
129
+ });
130
+
131
+ cache.set(cacheKey, {date: Date.now(), cachedResponse});
132
+ debug(`${cyan('CACHE SAVED')} :: ${log}`);
133
+
134
+ return res;
135
+ });
136
+ };
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@k03mad/request",
3
+ "version": "1.0.0",
4
+ "description": "Request library",
5
+ "maintainers": [
6
+ "Kirill Molchanov <k03.mad@gmail.com"
7
+ ],
8
+ "main": "app/index.js",
9
+ "repository": "k03mad/request",
10
+ "license": "MIT",
11
+ "type": "module",
12
+ "engines": {
13
+ "node": ">=20"
14
+ },
15
+ "dependencies": {
16
+ "chalk": "5.3.0",
17
+ "debug": "4.3.4",
18
+ "got": "13.0.0",
19
+ "p-queue": "7.3.4",
20
+ "pretty-bytes": "6.1.1"
21
+ },
22
+ "devDependencies": {
23
+ "@k03mad/eslint-config": "12.0.4",
24
+ "eslint": "8.45.0",
25
+ "eslint-plugin-import": "2.27.5",
26
+ "eslint-plugin-jsdoc": "46.4.4",
27
+ "eslint-plugin-n": "16.0.1",
28
+ "eslint-plugin-simple-import-sort": "10.0.0",
29
+ "eslint-plugin-sort-destructure-keys": "1.5.0",
30
+ "eslint-plugin-unicorn": "48.0.0",
31
+ "husky": "8.0.3"
32
+ },
33
+ "scripts": {
34
+ "lint": "eslint ./ --report-unused-disable-directives",
35
+ "clean": "rm -rfv ./node_modules || true",
36
+ "setup": "npm run clean && npm i",
37
+ "prepare": "husky install"
38
+ }
39
+ }