@krainovsd/js-helpers 0.15.2 → 0.16.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/lib/cjs/index.cjs +658 -560
- package/lib/cjs/index.cjs.map +1 -1
- package/lib/esm/{lib/api/middlewares/console-post-middleware.js → api/after/logger-after-handler.js} +5 -5
- package/lib/esm/api/after/logger-after-handler.js.map +1 -0
- package/lib/esm/api/api.constants.js +23 -0
- package/lib/esm/api/api.constants.js.map +1 -0
- package/lib/esm/api/api.js +343 -0
- package/lib/esm/api/api.js.map +1 -0
- package/lib/esm/{lib/api/middlewares/console-middleware.js → api/before/logger-before-handler.js} +4 -4
- package/lib/esm/api/before/logger-before-handler.js.map +1 -0
- package/lib/esm/{lib/api/middlewares/oauth-middleware.js → api/before/oauth-before-handler.js} +15 -15
- package/lib/esm/api/before/oauth-before-handler.js.map +1 -0
- package/lib/esm/{lib/api/oauth/token.js → api/oauth.js} +33 -27
- package/lib/esm/api/oauth.js.map +1 -0
- package/lib/esm/constants/errors.js +16 -0
- package/lib/esm/constants/errors.js.map +1 -0
- package/lib/esm/constants/index.js +27 -0
- package/lib/esm/constants/index.js.map +1 -0
- package/lib/esm/index.js +9 -8
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/lib/colors/get-color-format.js +1 -2
- package/lib/esm/lib/colors/get-color-format.js.map +1 -1
- package/lib/esm/lib/colors/take-opacity-colors.js +1 -2
- package/lib/esm/lib/colors/take-opacity-colors.js.map +1 -1
- package/lib/esm/lib/colors/transform-to-color.js +1 -2
- package/lib/esm/lib/colors/transform-to-color.js.map +1 -1
- package/lib/esm/lib/date/get-date-by-rules.js +1 -2
- package/lib/esm/lib/date/get-date-by-rules.js.map +1 -1
- package/lib/esm/lib/date/is-yesterday.js +0 -1
- package/lib/esm/lib/date/is-yesterday.js.map +1 -1
- package/lib/esm/lib/utils/build-query-string.js.map +1 -1
- package/lib/esm/lib/utils/{create-url-with-params.js → create-url-with-queries.js} +3 -3
- package/lib/esm/lib/utils/create-url-with-queries.js.map +1 -0
- package/lib/esm/lib/utils/field-view-format.js +1 -2
- package/lib/esm/lib/utils/field-view-format.js.map +1 -1
- package/lib/index.d.ts +226 -171
- package/package.json +4 -2
- package/lib/esm/constants/api.js +0 -10
- package/lib/esm/constants/api.js.map +0 -1
- package/lib/esm/constants/colors.js +0 -9
- package/lib/esm/constants/colors.js.map +0 -1
- package/lib/esm/constants/date.js +0 -11
- package/lib/esm/constants/date.js.map +0 -1
- package/lib/esm/constants/fields.js +0 -11
- package/lib/esm/constants/fields.js.map +0 -1
- package/lib/esm/lib/api/constants.js +0 -4
- package/lib/esm/lib/api/constants.js.map +0 -1
- package/lib/esm/lib/api/core.js +0 -187
- package/lib/esm/lib/api/core.js.map +0 -1
- package/lib/esm/lib/api/middlewares/console-middleware.js.map +0 -1
- package/lib/esm/lib/api/middlewares/console-post-middleware.js.map +0 -1
- package/lib/esm/lib/api/middlewares/index.js +0 -64
- package/lib/esm/lib/api/middlewares/index.js.map +0 -1
- package/lib/esm/lib/api/middlewares/oauth-middleware.js.map +0 -1
- package/lib/esm/lib/api/oauth/token.js.map +0 -1
- package/lib/esm/lib/api/oauth/user.js +0 -35
- package/lib/esm/lib/api/oauth/user.js.map +0 -1
- package/lib/esm/lib/utils/create-url-with-params.js.map +0 -1
package/lib/esm/{lib/api/middlewares/console-post-middleware.js → api/after/logger-after-handler.js}
RENAMED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { RESPONSE_DATA_SYMBOL } from '../constants.js';
|
|
1
|
+
import { RESPONSE_DATA_SYMBOL } from '../api.constants.js';
|
|
2
2
|
|
|
3
|
-
function
|
|
4
|
-
return (response) => {
|
|
3
|
+
function loggerAfterHandler(options = {}) {
|
|
4
|
+
return (request, response) => {
|
|
5
5
|
return new Promise((resolve) => {
|
|
6
6
|
void (async function logger() {
|
|
7
7
|
try {
|
|
@@ -51,5 +51,5 @@ function generateConsolePostMiddleware(options = {}) {
|
|
|
51
51
|
};
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
export {
|
|
55
|
-
//# sourceMappingURL=
|
|
54
|
+
export { loggerAfterHandler };
|
|
55
|
+
//# sourceMappingURL=logger-after-handler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger-after-handler.js","sources":["../../../../src/api/after/logger-after-handler.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport type { Headers as NodeHeaders, Response as NodeResponse } from \"node-fetch\";\nimport { RESPONSE_DATA_SYMBOL } from \"../api.constants\";\nimport type { AfterHandler } from \"../api.types\";\n\nexport type LoggerAfterHandlerOptions = {\n filter?: (response: Response | NodeResponse | undefined) => boolean;\n filterStatus?: (status: number) => boolean;\n filterUrl?: (url: string) => boolean;\n filterHeaders?: (headers: Headers | NodeHeaders) => boolean;\n};\n\nexport function loggerAfterHandler(options: LoggerAfterHandlerOptions = {}): AfterHandler {\n return (request, response) => {\n return new Promise((resolve) => {\n void (async function logger() {\n try {\n if (\n !response ||\n (options.filter && !options.filter(response)) ||\n (options.filterStatus && !options.filterStatus(response.status)) ||\n (options.filterUrl && !options.filterUrl(response.url)) ||\n (options.filterHeaders && !options.filterHeaders(response.headers))\n ) {\n resolve(true);\n\n return;\n }\n\n const contentType = response.headers.get(\"content-type\");\n let result;\n if (contentType?.includes?.(\"text\")) {\n result = await response.text();\n } else if (contentType?.includes?.(\"json\")) {\n result = await response.json();\n } else {\n result = await response.blob();\n }\n\n Object.defineProperty(response, RESPONSE_DATA_SYMBOL, {\n value: result,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n\n console.log({\n url: response.url,\n status: response.status,\n headers: response.headers,\n body: result,\n });\n\n resolve(true);\n } catch {\n if (response) {\n console.log({ url: response.url, status: response.status, headers: response.headers });\n }\n\n resolve(true);\n }\n })().finally(() => {\n resolve(true);\n });\n });\n };\n}\n"],"names":[],"mappings":";;AAYgB,SAAA,kBAAkB,CAAC,OAAA,GAAqC,EAAE,EAA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AC,GAAG,CAAC;wBACV,GAAG,EAAE,QAAQ,CAAC,GAAG;wBACjB,MAAM,EAAE,QAAQ,CAAC,MAAM;wBACvB,OAAO,EAAE,QAAQ,CAAC,OAAO;AACzB,wBAAA,IAAI,EAAE,MAAM;AACb,qBAAA,CAAC;oBAEF,OAAO,CAAC,IAAI,CAAC;;AACb,gBAAA,MAAM;oBACN,IAAI,QAAQ,EAAE;wBACZ,OAAO,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC;;oBAGxF,OAAO,CAAC,IAAI,CAAC;;AAEjB,aAAC,GAAG,CAAC,OAAO,CAAC,MAAK;gBAChB,OAAO,CAAC,IAAI,CAAC;AACf,aAAC,CAAC;AACJ,SAAC,CAAC;AACJ,KAAC;AACH;;;;"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
const RESPONSE_DATA_SYMBOL = Symbol("response data");
|
|
2
|
+
const REQUEST_ERROR = {
|
|
3
|
+
HTTP_ERROR: "http",
|
|
4
|
+
NETWORK_ERROR: "network",
|
|
5
|
+
TIMEOUT_ERROR: "timeout",
|
|
6
|
+
ABORT_ERROR: "abort",
|
|
7
|
+
VALIDATION_ERROR: "validation",
|
|
8
|
+
CACHE_ERROR: "cache",
|
|
9
|
+
UNKNOWN_ERROR: "unknown",
|
|
10
|
+
};
|
|
11
|
+
class OauthState {
|
|
12
|
+
_fetching = false;
|
|
13
|
+
get fetching() {
|
|
14
|
+
return this._fetching;
|
|
15
|
+
}
|
|
16
|
+
set fetching(value) {
|
|
17
|
+
this._fetching = value;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const OAUTH_STATE = new OauthState();
|
|
21
|
+
|
|
22
|
+
export { OAUTH_STATE, REQUEST_ERROR, RESPONSE_DATA_SYMBOL };
|
|
23
|
+
//# sourceMappingURL=api.constants.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api.constants.js","sources":["../../../src/api/api.constants.ts"],"sourcesContent":["export const RESPONSE_DATA_SYMBOL = Symbol(\"response data\");\nexport const REQUEST_ERROR = {\n HTTP_ERROR: \"http\",\n NETWORK_ERROR: \"network\",\n TIMEOUT_ERROR: \"timeout\",\n ABORT_ERROR: \"abort\",\n VALIDATION_ERROR: \"validation\",\n CACHE_ERROR: \"cache\",\n UNKNOWN_ERROR: \"unknown\",\n} as const;\n\nclass OauthState {\n private _fetching: boolean = false;\n\n get fetching() {\n return this._fetching;\n }\n\n set fetching(value: boolean) {\n this._fetching = value;\n }\n}\nexport const OAUTH_STATE = new OauthState();\n"],"names":[],"mappings":"MAAa,oBAAoB,GAAG,MAAM,CAAC,eAAe;AAC7C,MAAA,aAAa,GAAG;AAC3B,IAAA,UAAU,EAAE,MAAM;AAClB,IAAA,aAAa,EAAE,SAAS;AACxB,IAAA,aAAa,EAAE,SAAS;AACxB,IAAA,WAAW,EAAE,OAAO;AACpB,IAAA,gBAAgB,EAAE,YAAY;AAC9B,IAAA,WAAW,EAAE,OAAO;AACpB,IAAA,aAAa,EAAE,SAAS;;AAG1B,MAAM,UAAU,CAAA;IACN,SAAS,GAAY,KAAK;AAElC,IAAA,IAAI,QAAQ,GAAA;QACV,OAAO,IAAI,CAAC,SAAS;;IAGvB,IAAI,QAAQ,CAAC,KAAc,EAAA;AACzB,QAAA,IAAI,CAAC,SAAS,GAAG,KAAK;;AAEzB;AACY,MAAA,WAAW,GAAG,IAAI,UAAU;;;;"}
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
import { ResponseError } from '../constants/errors.js';
|
|
2
|
+
import { IS_BROWSER } from '../constants/environment.js';
|
|
3
|
+
import { downloadFile } from '../lib/browser/download-file.js';
|
|
4
|
+
import { isArray } from '../lib/typings/is-array.js';
|
|
5
|
+
import { isString } from '../lib/typings/is-string.js';
|
|
6
|
+
import 'dayjs';
|
|
7
|
+
import '../lib/date/is-today.js';
|
|
8
|
+
import '../lib/date/is-tomorrow.js';
|
|
9
|
+
import '../lib/date/is-yesterday.js';
|
|
10
|
+
import { wait } from '../lib/utils/wait.js';
|
|
11
|
+
import { createURLWithQueries } from '../lib/utils/create-url-with-queries.js';
|
|
12
|
+
import 'lodash/get';
|
|
13
|
+
import 'lodash/set';
|
|
14
|
+
import { REQUEST_ERROR, RESPONSE_DATA_SYMBOL } from './api.constants.js';
|
|
15
|
+
import { refetchAfterOauth } from './oauth.js';
|
|
16
|
+
|
|
17
|
+
function createFetchClient(options) {
|
|
18
|
+
let client = options.client;
|
|
19
|
+
let oauthOptions = options.oauthOptions;
|
|
20
|
+
let beforeHandlers = options.beforeHandlers;
|
|
21
|
+
let afterHandlers = options.afterHandlers;
|
|
22
|
+
let retries = options.retries;
|
|
23
|
+
let timeout = options.timeout;
|
|
24
|
+
function recreate(options) {
|
|
25
|
+
if ("client" in options) {
|
|
26
|
+
client = options.client;
|
|
27
|
+
}
|
|
28
|
+
if ("oauthOptions" in options) {
|
|
29
|
+
oauthOptions = options.oauthOptions;
|
|
30
|
+
}
|
|
31
|
+
if ("beforeHandlers" in options) {
|
|
32
|
+
beforeHandlers = options.beforeHandlers;
|
|
33
|
+
}
|
|
34
|
+
if ("afterHandlers" in options) {
|
|
35
|
+
afterHandlers = options.afterHandlers;
|
|
36
|
+
}
|
|
37
|
+
if ("retries" in options) {
|
|
38
|
+
retries = options.retries;
|
|
39
|
+
}
|
|
40
|
+
if ("timeout" in options) {
|
|
41
|
+
timeout = options.timeout;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
async function handleRequest(request) {
|
|
45
|
+
const timeoutController = new AbortController();
|
|
46
|
+
const requestController = new AbortController();
|
|
47
|
+
const requestTimeout = request.timeout ?? timeout;
|
|
48
|
+
const requestRetries = request.retries ?? retries;
|
|
49
|
+
try {
|
|
50
|
+
if (request.delay) {
|
|
51
|
+
await wait(request.delay);
|
|
52
|
+
}
|
|
53
|
+
if (request.mock) {
|
|
54
|
+
const mock = typeof request.mock === "function" ? request.mock() : request.mock;
|
|
55
|
+
const transformedResult = request.transformIncomingData
|
|
56
|
+
? request.transformIncomingData(mock)
|
|
57
|
+
: mock;
|
|
58
|
+
return { data: transformedResult, error: null, response: null };
|
|
59
|
+
}
|
|
60
|
+
if (requestTimeout != undefined && requestTimeout != 0) {
|
|
61
|
+
setTimeout(() => {
|
|
62
|
+
if (requestController.signal.aborted)
|
|
63
|
+
return;
|
|
64
|
+
timeoutController.abort();
|
|
65
|
+
}, requestTimeout);
|
|
66
|
+
timeoutController.signal.addEventListener("abort", () => requestController.abort(), {
|
|
67
|
+
once: true,
|
|
68
|
+
signal: requestController.signal,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
if (request.signal) {
|
|
72
|
+
request.signal.addEventListener("abort", () => requestController.abort(), {
|
|
73
|
+
once: true,
|
|
74
|
+
signal: requestController.signal,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
{
|
|
78
|
+
let handlers = [];
|
|
79
|
+
if (request.beforeHandlers) {
|
|
80
|
+
handlers = request.beforeHandlers;
|
|
81
|
+
}
|
|
82
|
+
else if (beforeHandlers) {
|
|
83
|
+
handlers = beforeHandlers;
|
|
84
|
+
}
|
|
85
|
+
if (request.additionalBeforeHandlers) {
|
|
86
|
+
handlers = handlers.concat(request.additionalBeforeHandlers);
|
|
87
|
+
}
|
|
88
|
+
if (handlers.length > 0) {
|
|
89
|
+
await executeBeforeHandlers(handlers, request);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const { method, body, path, queries, headers = {}, refetchNoAuth = true } = request;
|
|
93
|
+
const url = createURLWithQueries({ baseURL: path, params: queries });
|
|
94
|
+
let [, requestContentType] = Object.entries(headers).find(([header]) => header.toLowerCase() === "content-type") ?? [];
|
|
95
|
+
if (isArray(requestContentType)) {
|
|
96
|
+
requestContentType = requestContentType[0];
|
|
97
|
+
}
|
|
98
|
+
let preparedBody = body;
|
|
99
|
+
if (request.transformOutcomingData) {
|
|
100
|
+
preparedBody = request.transformOutcomingData(body);
|
|
101
|
+
}
|
|
102
|
+
if (requestContentType == undefined &&
|
|
103
|
+
!(preparedBody instanceof FormData) &&
|
|
104
|
+
preparedBody != undefined &&
|
|
105
|
+
!isString(preparedBody)) {
|
|
106
|
+
headers["content-type"] = "application/json; charset=UTF-8";
|
|
107
|
+
}
|
|
108
|
+
if ((requestContentType == undefined || requestContentType.toLowerCase().includes("json")) &&
|
|
109
|
+
preparedBody != undefined &&
|
|
110
|
+
!(preparedBody instanceof FormData) &&
|
|
111
|
+
!isString(preparedBody)) {
|
|
112
|
+
preparedBody = JSON.stringify(preparedBody);
|
|
113
|
+
}
|
|
114
|
+
const response = await client(url, {
|
|
115
|
+
method,
|
|
116
|
+
body: preparedBody,
|
|
117
|
+
headers: headers,
|
|
118
|
+
signal: requestController.signal,
|
|
119
|
+
cache: request.cache,
|
|
120
|
+
credentials: request.credentials,
|
|
121
|
+
integrity: request.integrity,
|
|
122
|
+
keepalive: request.keepalive,
|
|
123
|
+
mode: request.mode,
|
|
124
|
+
priority: request.priority,
|
|
125
|
+
redirect: request.redirect,
|
|
126
|
+
referrer: request.referrer,
|
|
127
|
+
referrerPolicy: request.referrerPolicy,
|
|
128
|
+
compress: request.compress,
|
|
129
|
+
follow: request.follow,
|
|
130
|
+
});
|
|
131
|
+
{
|
|
132
|
+
let handlers = [];
|
|
133
|
+
if (request.afterHandlers) {
|
|
134
|
+
handlers = request.afterHandlers;
|
|
135
|
+
}
|
|
136
|
+
else if (afterHandlers) {
|
|
137
|
+
handlers = afterHandlers;
|
|
138
|
+
}
|
|
139
|
+
if (request.additionalAfterHandlers) {
|
|
140
|
+
handlers = handlers.concat(request.additionalAfterHandlers);
|
|
141
|
+
}
|
|
142
|
+
if (handlers.length > 0) {
|
|
143
|
+
await executeAfterHandlers(handlers, request, response);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (!response.ok) {
|
|
147
|
+
if (response.status === 304) {
|
|
148
|
+
const error = new ResponseError({
|
|
149
|
+
message: REQUEST_ERROR.CACHE_ERROR,
|
|
150
|
+
status: response.status,
|
|
151
|
+
headers: Object.fromEntries(response.headers.entries()),
|
|
152
|
+
});
|
|
153
|
+
request.onError?.(REQUEST_ERROR.CACHE_ERROR, error);
|
|
154
|
+
return { data: error, error: REQUEST_ERROR.CACHE_ERROR, response };
|
|
155
|
+
}
|
|
156
|
+
if (response.status === 401 && refetchNoAuth && oauthOptions) {
|
|
157
|
+
return await refetchAfterOauth(oauthOptions, () => handleRequest({ ...request, refetchNoAuth: false }));
|
|
158
|
+
}
|
|
159
|
+
if (request.defaultResponse) {
|
|
160
|
+
const defaultResponse = typeof request.defaultResponse === "function"
|
|
161
|
+
? request.defaultResponse()
|
|
162
|
+
: request.defaultResponse;
|
|
163
|
+
const transformedResult = request.transformIncomingData
|
|
164
|
+
? request.transformIncomingData(defaultResponse)
|
|
165
|
+
: defaultResponse;
|
|
166
|
+
return {
|
|
167
|
+
data: transformedResult,
|
|
168
|
+
error: null,
|
|
169
|
+
response: null,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
if (requestRetries && requestRetries.length > 0) {
|
|
173
|
+
await wait(requestRetries[0]);
|
|
174
|
+
return await handleRequest({ ...request, retries: requestRetries.slice(1) });
|
|
175
|
+
}
|
|
176
|
+
let result;
|
|
177
|
+
try {
|
|
178
|
+
const contentType = response.headers.get("content-type");
|
|
179
|
+
if (RESPONSE_DATA_SYMBOL in response) {
|
|
180
|
+
result = response[RESPONSE_DATA_SYMBOL];
|
|
181
|
+
}
|
|
182
|
+
else if (contentType?.includes?.("text")) {
|
|
183
|
+
result = await response.text();
|
|
184
|
+
}
|
|
185
|
+
else if (contentType?.includes?.("json")) {
|
|
186
|
+
result = await response.json();
|
|
187
|
+
}
|
|
188
|
+
else {
|
|
189
|
+
result = await response.blob();
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
catch { }
|
|
193
|
+
const error = new ResponseError({
|
|
194
|
+
status: response.status,
|
|
195
|
+
message: REQUEST_ERROR.HTTP_ERROR,
|
|
196
|
+
description: result,
|
|
197
|
+
headers: Object.fromEntries(response.headers.entries()),
|
|
198
|
+
});
|
|
199
|
+
request.onError?.(REQUEST_ERROR.HTTP_ERROR, error);
|
|
200
|
+
return {
|
|
201
|
+
data: error,
|
|
202
|
+
error: REQUEST_ERROR.HTTP_ERROR,
|
|
203
|
+
response,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
if (request.download) {
|
|
207
|
+
const data = await response.blob();
|
|
208
|
+
const mimeType = response.headers.get("content-type");
|
|
209
|
+
const fileName = response.headers.get("content-disposition");
|
|
210
|
+
if (!mimeType) {
|
|
211
|
+
console.warn("couldn't download file because content-type header is not exist");
|
|
212
|
+
}
|
|
213
|
+
else if (!fileName) {
|
|
214
|
+
console.warn("couldn't download file because content-disposition header is not exist");
|
|
215
|
+
}
|
|
216
|
+
if (IS_BROWSER && mimeType && fileName)
|
|
217
|
+
downloadFile({
|
|
218
|
+
data: data,
|
|
219
|
+
fileName,
|
|
220
|
+
mimeType,
|
|
221
|
+
});
|
|
222
|
+
return {
|
|
223
|
+
data: data,
|
|
224
|
+
error: null,
|
|
225
|
+
response,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
const contentType = response.headers.get("content-type");
|
|
229
|
+
let result = undefined;
|
|
230
|
+
if (RESPONSE_DATA_SYMBOL in response) {
|
|
231
|
+
result = response[RESPONSE_DATA_SYMBOL];
|
|
232
|
+
}
|
|
233
|
+
else if (contentType?.includes?.("text")) {
|
|
234
|
+
result = (await response.text());
|
|
235
|
+
}
|
|
236
|
+
else if (contentType?.includes?.("json")) {
|
|
237
|
+
result = (await response.json());
|
|
238
|
+
}
|
|
239
|
+
else {
|
|
240
|
+
result = (await response.blob());
|
|
241
|
+
}
|
|
242
|
+
const transformedResult = request.transformIncomingData
|
|
243
|
+
? request.transformIncomingData(result)
|
|
244
|
+
: result;
|
|
245
|
+
return {
|
|
246
|
+
data: transformedResult,
|
|
247
|
+
error: null,
|
|
248
|
+
response,
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
catch (err) {
|
|
252
|
+
if (request.defaultResponse) {
|
|
253
|
+
const defaultResponse = typeof request.defaultResponse === "function"
|
|
254
|
+
? request.defaultResponse()
|
|
255
|
+
: request.defaultResponse;
|
|
256
|
+
const transformedResult = request.transformIncomingData
|
|
257
|
+
? request.transformIncomingData(defaultResponse)
|
|
258
|
+
: defaultResponse;
|
|
259
|
+
return {
|
|
260
|
+
data: transformedResult,
|
|
261
|
+
error: null,
|
|
262
|
+
response: null,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
if (requestRetries && requestRetries.length > 0 && request?.signal?.aborted !== true) {
|
|
266
|
+
await wait(requestRetries[0]);
|
|
267
|
+
return await handleRequest({ ...request, retries: requestRetries.slice(1) });
|
|
268
|
+
}
|
|
269
|
+
if (err instanceof TypeError) {
|
|
270
|
+
const error = new ResponseError({
|
|
271
|
+
message: REQUEST_ERROR.NETWORK_ERROR,
|
|
272
|
+
status: 0,
|
|
273
|
+
description: String(err.message),
|
|
274
|
+
});
|
|
275
|
+
request.onError?.(REQUEST_ERROR.NETWORK_ERROR, error);
|
|
276
|
+
return { data: error, error: REQUEST_ERROR.NETWORK_ERROR, response: null };
|
|
277
|
+
}
|
|
278
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
279
|
+
if (timeoutController.signal.aborted) {
|
|
280
|
+
const error = new ResponseError({
|
|
281
|
+
message: REQUEST_ERROR.TIMEOUT_ERROR,
|
|
282
|
+
status: 0,
|
|
283
|
+
});
|
|
284
|
+
request.onError?.(REQUEST_ERROR.TIMEOUT_ERROR, error);
|
|
285
|
+
return { data: error, error: REQUEST_ERROR.TIMEOUT_ERROR, response: null };
|
|
286
|
+
}
|
|
287
|
+
const error = new ResponseError({
|
|
288
|
+
message: REQUEST_ERROR.ABORT_ERROR,
|
|
289
|
+
status: 0,
|
|
290
|
+
});
|
|
291
|
+
request.onError?.(REQUEST_ERROR.ABORT_ERROR, error);
|
|
292
|
+
return { data: error, error: REQUEST_ERROR.ABORT_ERROR, response: null };
|
|
293
|
+
}
|
|
294
|
+
const error = new ResponseError({
|
|
295
|
+
message: REQUEST_ERROR.UNKNOWN_ERROR,
|
|
296
|
+
status: 0,
|
|
297
|
+
description: String(err),
|
|
298
|
+
});
|
|
299
|
+
request.onError?.(REQUEST_ERROR.UNKNOWN_ERROR, error);
|
|
300
|
+
return { data: error, error: REQUEST_ERROR.UNKNOWN_ERROR, response: null };
|
|
301
|
+
}
|
|
302
|
+
finally {
|
|
303
|
+
requestController.abort();
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
async function requestWithArrayResponse(request) {
|
|
307
|
+
const response = await handleRequest(request);
|
|
308
|
+
return [response.data, response.error, response.response];
|
|
309
|
+
}
|
|
310
|
+
async function requestWithObjectResponse(request) {
|
|
311
|
+
return handleRequest(request);
|
|
312
|
+
}
|
|
313
|
+
return {
|
|
314
|
+
requestWithArrayResponse,
|
|
315
|
+
requestWithObjectResponse,
|
|
316
|
+
recreate,
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
function executeBeforeHandlers(handlers, request) {
|
|
320
|
+
return new Promise((resolve) => {
|
|
321
|
+
void (async () => {
|
|
322
|
+
for (const handler of handlers) {
|
|
323
|
+
// eslint-disable-next-line no-await-in-loop
|
|
324
|
+
await handler(request);
|
|
325
|
+
}
|
|
326
|
+
resolve(1);
|
|
327
|
+
})();
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
function executeAfterHandlers(handlers, request, response) {
|
|
331
|
+
return new Promise((resolve) => {
|
|
332
|
+
void (async () => {
|
|
333
|
+
for (const handler of handlers) {
|
|
334
|
+
// eslint-disable-next-line no-await-in-loop
|
|
335
|
+
await handler(request, response);
|
|
336
|
+
}
|
|
337
|
+
resolve(1);
|
|
338
|
+
})();
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export { createFetchClient };
|
|
343
|
+
//# sourceMappingURL=api.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api.js","sources":["../../../src/api/api.ts"],"sourcesContent":["import type {\n HeadersInit,\n BodyInit as NodeBodyInit,\n RequestInfo as NodeRequestInfo,\n RequestInit as NodeRequestInit,\n Response as NodeResponse,\n} from \"node-fetch\";\nimport { IS_BROWSER, ResponseError } from \"../constants\";\nimport { createURLWithQueries, downloadFile, isArray, isString, wait } from \"../lib\";\nimport { REQUEST_ERROR, RESPONSE_DATA_SYMBOL } from \"./api.constants\";\nimport type {\n AfterHandler,\n BeforeHandler,\n OauthOptions,\n RequestError,\n RequestInterface,\n} from \"./api.types\";\nimport { refetchAfterOauth } from \"./oauth\";\n\ntype CreateRequestClientInstance = {\n client:\n | ((url: URL | NodeRequestInfo, init?: NodeRequestInit) => Promise<NodeResponse>)\n | typeof fetch;\n oauthOptions?: OauthOptions;\n beforeHandlers?: BeforeHandler[];\n afterHandlers?: AfterHandler[];\n retries?: number[];\n timeout?: number;\n};\n\nexport type RequestInstance = {\n <IncomingApi, Incoming = IncomingApi, Outcoming = unknown, OutcomingApi = Outcoming>(\n request: RequestInterface<IncomingApi, Incoming, Outcoming, OutcomingApi>,\n ): Promise<Incoming>;\n recreate: (options: CreateRequestClientInstance) => void;\n};\n\nexport function createFetchClient(options: CreateRequestClientInstance) {\n let client:\n | ((url: URL | NodeRequestInfo, init?: NodeRequestInit) => Promise<NodeResponse>)\n | typeof fetch = options.client;\n let oauthOptions: OauthOptions | undefined = options.oauthOptions;\n let beforeHandlers: BeforeHandler[] | undefined = options.beforeHandlers;\n let afterHandlers: AfterHandler[] | undefined = options.afterHandlers;\n let retries: number[] | undefined = options.retries;\n let timeout: number | undefined = options.timeout;\n\n function recreate(options: CreateRequestClientInstance) {\n if (\"client\" in options) {\n client = options.client;\n }\n if (\"oauthOptions\" in options) {\n oauthOptions = options.oauthOptions;\n }\n if (\"beforeHandlers\" in options) {\n beforeHandlers = options.beforeHandlers;\n }\n if (\"afterHandlers\" in options) {\n afterHandlers = options.afterHandlers;\n }\n if (\"retries\" in options) {\n retries = options.retries;\n }\n if (\"timeout\" in options) {\n timeout = options.timeout;\n }\n }\n\n async function handleRequest<\n IncomingApi = unknown,\n Incoming = IncomingApi,\n Outcoming = unknown,\n OutcomingApi = Outcoming,\n >(\n request: RequestInterface<IncomingApi, Incoming, Outcoming, OutcomingApi>,\n ): Promise<\n | {\n data: ResponseError;\n error: RequestError;\n response: Response | NodeResponse | null;\n }\n | { data: Incoming; error: null; response: Response | NodeResponse | null }\n > {\n const timeoutController = new AbortController();\n const requestController = new AbortController();\n const requestTimeout = request.timeout ?? timeout;\n const requestRetries = request.retries ?? retries;\n\n try {\n if (request.delay) {\n await wait(request.delay);\n }\n if (request.mock) {\n const mock: unknown =\n typeof request.mock === \"function\" ? (request.mock as () => Incoming)() : request.mock;\n\n const transformedResult = request.transformIncomingData\n ? request.transformIncomingData(mock as IncomingApi)\n : (mock as Incoming);\n\n return { data: transformedResult, error: null, response: null };\n }\n\n if (requestTimeout != undefined && requestTimeout != 0) {\n setTimeout(() => {\n if (requestController.signal.aborted) return;\n timeoutController.abort();\n }, requestTimeout);\n timeoutController.signal.addEventListener(\"abort\", () => requestController.abort(), {\n once: true,\n signal: requestController.signal,\n });\n }\n if (request.signal) {\n request.signal.addEventListener(\"abort\", () => requestController.abort(), {\n once: true,\n signal: requestController.signal,\n });\n }\n\n {\n let handlers: BeforeHandler[] = [];\n if (request.beforeHandlers) {\n handlers = request.beforeHandlers;\n } else if (beforeHandlers) {\n handlers = beforeHandlers;\n }\n if (request.additionalBeforeHandlers) {\n handlers = handlers.concat(request.additionalBeforeHandlers);\n }\n\n if (handlers.length > 0) {\n await executeBeforeHandlers(handlers, request);\n }\n }\n\n const { method, body, path, queries, headers = {}, refetchNoAuth = true } = request;\n\n const url = createURLWithQueries({ baseURL: path, params: queries });\n let [, requestContentType] =\n Object.entries(headers).find(([header]) => header.toLowerCase() === \"content-type\") ?? [];\n if (isArray(requestContentType)) {\n requestContentType = requestContentType[0];\n }\n\n let preparedBody: OutcomingApi = body as OutcomingApi;\n if (request.transformOutcomingData) {\n preparedBody = request.transformOutcomingData(body as Outcoming);\n }\n\n if (\n requestContentType == undefined &&\n !(preparedBody instanceof FormData) &&\n preparedBody != undefined &&\n !isString(preparedBody)\n ) {\n headers[\"content-type\"] = \"application/json; charset=UTF-8\";\n }\n\n if (\n (requestContentType == undefined || requestContentType.toLowerCase().includes(\"json\")) &&\n preparedBody != undefined &&\n !(preparedBody instanceof FormData) &&\n !isString(preparedBody)\n ) {\n preparedBody = JSON.stringify(preparedBody) as OutcomingApi;\n }\n const response: Response | NodeResponse | undefined = await client(url, {\n method,\n body: preparedBody as ((BodyInit | null) & NodeBodyInit) | undefined,\n headers: headers as globalThis.HeadersInit & HeadersInit,\n signal: requestController.signal as\n | (AbortSignal & NodeRequestInit[\"signal\"])\n | null\n | undefined,\n cache: request.cache,\n credentials: request.credentials,\n integrity: request.integrity,\n keepalive: request.keepalive,\n mode: request.mode,\n priority: request.priority,\n redirect: request.redirect,\n referrer: request.referrer,\n referrerPolicy: request.referrerPolicy,\n compress: request.compress,\n follow: request.follow,\n });\n\n {\n let handlers: AfterHandler[] = [];\n if (request.afterHandlers) {\n handlers = request.afterHandlers;\n } else if (afterHandlers) {\n handlers = afterHandlers;\n }\n if (request.additionalAfterHandlers) {\n handlers = handlers.concat(request.additionalAfterHandlers);\n }\n\n if (handlers.length > 0) {\n await executeAfterHandlers(handlers, request, response);\n }\n }\n\n if (!response.ok) {\n if (response.status === 304) {\n const error = new ResponseError({\n message: REQUEST_ERROR.CACHE_ERROR,\n status: response.status,\n headers: Object.fromEntries(response.headers.entries()),\n });\n request.onError?.(REQUEST_ERROR.CACHE_ERROR, error);\n\n return { data: error, error: REQUEST_ERROR.CACHE_ERROR, response };\n }\n if (response.status === 401 && refetchNoAuth && oauthOptions) {\n return await refetchAfterOauth(oauthOptions, () =>\n handleRequest({ ...request, refetchNoAuth: false }),\n );\n }\n\n if (request.defaultResponse) {\n const defaultResponse: unknown =\n typeof request.defaultResponse === \"function\"\n ? (request.defaultResponse as () => Incoming)()\n : request.defaultResponse;\n\n const transformedResult = request.transformIncomingData\n ? request.transformIncomingData(defaultResponse as IncomingApi)\n : (defaultResponse as Incoming);\n\n return {\n data: transformedResult,\n error: null,\n response: null,\n };\n }\n if (requestRetries && requestRetries.length > 0) {\n await wait(requestRetries[0]);\n\n return await handleRequest({ ...request, retries: requestRetries.slice(1) });\n }\n\n let result;\n try {\n const contentType = response.headers.get(\"content-type\");\n\n if (RESPONSE_DATA_SYMBOL in response) {\n result = response[RESPONSE_DATA_SYMBOL];\n } else if (contentType?.includes?.(\"text\")) {\n result = await response.text();\n } else if (contentType?.includes?.(\"json\")) {\n result = await response.json();\n } else {\n result = await response.blob();\n }\n } catch {}\n\n const error = new ResponseError({\n status: response.status,\n message: REQUEST_ERROR.HTTP_ERROR,\n description: result,\n headers: Object.fromEntries(response.headers.entries()),\n });\n request.onError?.(REQUEST_ERROR.HTTP_ERROR, error);\n\n return {\n data: error,\n error: REQUEST_ERROR.HTTP_ERROR,\n response,\n };\n }\n\n if (request.download) {\n const data = await response.blob();\n const mimeType = response.headers.get(\"content-type\");\n const fileName = response.headers.get(\"content-disposition\");\n\n if (!mimeType) {\n console.warn(\"couldn't download file because content-type header is not exist\");\n } else if (!fileName) {\n console.warn(\"couldn't download file because content-disposition header is not exist\");\n }\n\n if (IS_BROWSER && mimeType && fileName)\n downloadFile({\n data: data as Blob,\n fileName,\n mimeType,\n });\n\n return {\n data: data as Incoming,\n error: null,\n response,\n };\n }\n\n const contentType = response.headers.get(\"content-type\");\n let result: Incoming | IncomingApi = undefined as Incoming | IncomingApi;\n\n if (RESPONSE_DATA_SYMBOL in response) {\n result = response[RESPONSE_DATA_SYMBOL] as Incoming | IncomingApi;\n } else if (contentType?.includes?.(\"text\")) {\n result = (await response.text()) as Incoming | IncomingApi;\n } else if (contentType?.includes?.(\"json\")) {\n result = (await response.json()) as Incoming | IncomingApi;\n } else {\n result = (await response.blob()) as Incoming | IncomingApi;\n }\n\n const transformedResult = request.transformIncomingData\n ? request.transformIncomingData(result as IncomingApi)\n : (result as Incoming);\n\n return {\n data: transformedResult,\n error: null,\n response,\n };\n } catch (err: unknown) {\n if (request.defaultResponse) {\n const defaultResponse: unknown =\n typeof request.defaultResponse === \"function\"\n ? (request.defaultResponse as () => Incoming)()\n : request.defaultResponse;\n\n const transformedResult = request.transformIncomingData\n ? request.transformIncomingData(defaultResponse as IncomingApi)\n : (defaultResponse as Incoming);\n\n return {\n data: transformedResult,\n error: null,\n response: null,\n };\n }\n if (requestRetries && requestRetries.length > 0 && request?.signal?.aborted !== true) {\n await wait(requestRetries[0]);\n\n return await handleRequest({ ...request, retries: requestRetries.slice(1) });\n }\n\n if (err instanceof TypeError) {\n const error = new ResponseError({\n message: REQUEST_ERROR.NETWORK_ERROR,\n status: 0,\n description: String(err.message),\n });\n request.onError?.(REQUEST_ERROR.NETWORK_ERROR, error);\n\n return { data: error, error: REQUEST_ERROR.NETWORK_ERROR, response: null };\n }\n\n if (err instanceof Error && err.name === \"AbortError\") {\n if (timeoutController.signal.aborted) {\n const error = new ResponseError({\n message: REQUEST_ERROR.TIMEOUT_ERROR,\n status: 0,\n });\n request.onError?.(REQUEST_ERROR.TIMEOUT_ERROR, error);\n\n return { data: error, error: REQUEST_ERROR.TIMEOUT_ERROR, response: null };\n }\n\n const error = new ResponseError({\n message: REQUEST_ERROR.ABORT_ERROR,\n status: 0,\n });\n request.onError?.(REQUEST_ERROR.ABORT_ERROR, error);\n\n return { data: error, error: REQUEST_ERROR.ABORT_ERROR, response: null };\n }\n\n const error = new ResponseError({\n message: REQUEST_ERROR.UNKNOWN_ERROR,\n status: 0,\n description: String(err),\n });\n request.onError?.(REQUEST_ERROR.UNKNOWN_ERROR, error);\n\n return { data: error, error: REQUEST_ERROR.UNKNOWN_ERROR, response: null };\n } finally {\n requestController.abort();\n }\n }\n\n async function requestWithArrayResponse<\n IncomingApi,\n Incoming = IncomingApi,\n Outcoming = unknown,\n OutcomingApi = Outcoming,\n >(\n request: RequestInterface<IncomingApi, Incoming, Outcoming, OutcomingApi>,\n ): Promise<\n | [ResponseError, RequestError, Response | NodeResponse | null]\n | [Incoming, null, Response | NodeResponse | null]\n > {\n const response = await handleRequest(request);\n\n return [response.data, response.error, response.response] as\n | [ResponseError, RequestError, Response | NodeResponse | null]\n | [Incoming, null, Response | NodeResponse | null];\n }\n\n async function requestWithObjectResponse<\n IncomingApi,\n Incoming = IncomingApi,\n Outcoming = unknown,\n OutcomingApi = Outcoming,\n >(\n request: RequestInterface<IncomingApi, Incoming, Outcoming, OutcomingApi>,\n ): Promise<\n | {\n data: ResponseError;\n error: RequestError;\n response: Response | NodeResponse | null;\n }\n | { data: Incoming; error: null; response: Response | NodeResponse | null }\n > {\n return handleRequest(request);\n }\n\n return {\n requestWithArrayResponse,\n requestWithObjectResponse,\n recreate,\n };\n}\n\nfunction executeBeforeHandlers<\n IncomingApi,\n Incoming = IncomingApi,\n Outcoming = unknown,\n OutcomingApi = Outcoming,\n>(\n handlers: BeforeHandler[],\n request: RequestInterface<IncomingApi, Incoming, Outcoming, OutcomingApi>,\n) {\n return new Promise((resolve) => {\n void (async () => {\n for (const handler of handlers) {\n // eslint-disable-next-line no-await-in-loop\n await handler(request);\n }\n\n resolve(1);\n })();\n });\n}\n\nfunction executeAfterHandlers<\n IncomingApi,\n Incoming = IncomingApi,\n Outcoming = unknown,\n OutcomingApi = Outcoming,\n>(\n handlers: AfterHandler[],\n request: RequestInterface<IncomingApi, Incoming, Outcoming, OutcomingApi>,\n response: Response | NodeResponse | undefined,\n) {\n return new Promise((resolve) => {\n void (async () => {\n for (const handler of handlers) {\n // eslint-disable-next-line no-await-in-loop\n await handler(request, response);\n }\n\n resolve(1);\n })();\n });\n}\n"],"names":[],"mappings":";;;;;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,OAAO,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC,QAAQ,CAEJ;;IAGtD,eAAe,yBAAyB,CAMtC,OAAyE,EAAA;AASzE,QAAA,OAAO,aAAa,CAAC,OAAO,CAAC;;IAG/B,OAAO;QACL,wBAAwB;QACxB,yBAAyB;QACzB,QAAQ;KACT;AACH;AAEA,SAAS,qBAAqB,CAM5B,QAAyB,EACzB,OAAyE,EAAA;AAEzE,IAAA,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,KAAI;QAC7B,KAAK,CAAC,YAAW;AACf,YAAA,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE;;AAE9B,gBAAA,MAAM,OAAO,CAAC,OAAO,CAAC;;YAGxB,OAAO,CAAC,CAAC,CAAC;SACX,GAAG;AACN,KAAC,CAAC;AACJ;AAEA,SAAS,oBAAoB,CAM3B,QAAwB,EACxB,OAAyE,EACzE,QAA6C,EAAA;AAE7C,IAAA,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,KAAI;QAC7B,KAAK,CAAC,YAAW;AACf,YAAA,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE;;AAE9B,gBAAA,MAAM,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC;;YAGlC,OAAO,CAAC,CAAC,CAAC;SACX,GAAG;AACN,KAAC,CAAC;AACJ;;;;"}
|
package/lib/esm/{lib/api/middlewares/console-middleware.js → api/before/logger-before-handler.js}
RENAMED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
function
|
|
1
|
+
function loggerBeforeHandler(options = {}) {
|
|
2
2
|
return (request) => {
|
|
3
3
|
return new Promise((resolve) => {
|
|
4
4
|
if ((options.filter &&
|
|
5
5
|
!options.filter(request)) ||
|
|
6
6
|
(options.filterHeaders && !options.filterHeaders(request.headers)) ||
|
|
7
7
|
(options.filterMethod && !options.filterMethod(request.method)) ||
|
|
8
|
-
(options.filterParams && !options.filterParams(request.
|
|
8
|
+
(options.filterParams && !options.filterParams(request.queries)) ||
|
|
9
9
|
(options.filterPath && !options.filterPath(request.path))) {
|
|
10
10
|
resolve(true);
|
|
11
11
|
return;
|
|
@@ -17,5 +17,5 @@ function generateConsoleMiddleware(options = {}) {
|
|
|
17
17
|
};
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
-
export {
|
|
21
|
-
//# sourceMappingURL=
|
|
20
|
+
export { loggerBeforeHandler };
|
|
21
|
+
//# sourceMappingURL=logger-before-handler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger-before-handler.js","sources":["../../../../src/api/before/logger-before-handler.ts"],"sourcesContent":["import type {\n BeforeHandler,\n RequestHeader,\n RequestInterface,\n RequestMethod,\n RequestQuery,\n} from \"../api.types\";\n\nexport type LoggerBeforeHandlerOptions = {\n filter?: (request: RequestInterface<unknown, unknown, unknown, unknown>) => boolean;\n filterPath?: (path: string) => boolean;\n filterMethod?: (method: RequestMethod) => boolean;\n filterParams?: (params?: RequestQuery) => boolean;\n filterHeaders?: (headers?: RequestHeader) => boolean;\n};\n\nexport function loggerBeforeHandler(options: LoggerBeforeHandlerOptions = {}): BeforeHandler {\n return (request) => {\n return new Promise((resolve) => {\n if (\n (options.filter &&\n !options.filter(request as RequestInterface<unknown, unknown, unknown, unknown>)) ||\n (options.filterHeaders && !options.filterHeaders(request.headers)) ||\n (options.filterMethod && !options.filterMethod(request.method)) ||\n (options.filterParams && !options.filterParams(request.queries)) ||\n (options.filterPath && !options.filterPath(request.path))\n ) {\n resolve(true);\n\n return;\n }\n // eslint-disable-next-line no-console\n console.log(request);\n resolve(true);\n });\n };\n}\n"],"names":[],"mappings":"AAgBgB,SAAA,mBAAmB,CAAC,OAAA,GAAsC,EAAE,EAAA;IAC1E,OAAO,CAAC,OAAO,KAAI;AACjB,QAAA,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,KAAI;YAC7B,IACE,CAAC,OAAO,CAAC,MAAM;AACb,gBAAA,CAAC,OAAO,CAAC,MAAM,CAAC,OAA+D,CAAC;AAClF,iBAAC,OAAO,CAAC,aAAa,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;AAClE,iBAAC,OAAO,CAAC,YAAY,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;AAC/D,iBAAC,OAAO,CAAC,YAAY,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;AAChE,iBAAC,OAAO,CAAC,UAAU,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,EACzD;gBACA,OAAO,CAAC,IAAI,CAAC;gBAEb;;;AAGF,YAAA,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC;YACpB,OAAO,CAAC,IAAI,CAAC;AACf,SAAC,CAAC;AACJ,KAAC;AACH;;;;"}
|
package/lib/esm/{lib/api/middlewares/oauth-middleware.js → api/before/oauth-before-handler.js}
RENAMED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import { waitUntil } from '../../utils/wait-until.js';
|
|
2
|
-
import '
|
|
1
|
+
import { waitUntil } from '../../lib/utils/wait-until.js';
|
|
2
|
+
import '../../constants/environment.js';
|
|
3
3
|
import 'dayjs';
|
|
4
|
-
import '../../date/is-today.js';
|
|
5
|
-
import '../../date/is-tomorrow.js';
|
|
6
|
-
import '../../date/is-yesterday.js';
|
|
4
|
+
import '../../lib/date/is-today.js';
|
|
5
|
+
import '../../lib/date/is-tomorrow.js';
|
|
6
|
+
import '../../lib/date/is-yesterday.js';
|
|
7
7
|
import 'lodash/get';
|
|
8
8
|
import 'lodash/set';
|
|
9
|
-
import { startWith } from '../../utils/start-with.js';
|
|
10
|
-
import {
|
|
9
|
+
import { startWith } from '../../lib/utils/start-with.js';
|
|
10
|
+
import { OAUTH_STATE } from '../api.constants.js';
|
|
11
|
+
import { getOauthTokenFromOtherWindow } from '../oauth.js';
|
|
11
12
|
|
|
12
|
-
|
|
13
|
-
const generateOauthMiddleware = (options) => async (request) => {
|
|
13
|
+
const oauthBeforeHandler = (options) => async (request) => {
|
|
14
14
|
if (!options.expiresTokenStorageName) {
|
|
15
15
|
throw new Error("Auth middleware hasn't required options");
|
|
16
16
|
}
|
|
@@ -23,12 +23,12 @@ const generateOauthMiddleware = (options) => async (request) => {
|
|
|
23
23
|
};
|
|
24
24
|
return;
|
|
25
25
|
}
|
|
26
|
-
if (
|
|
27
|
-
await waitUntil(() =>
|
|
26
|
+
if (OAUTH_STATE.fetching)
|
|
27
|
+
await waitUntil(() => OAUTH_STATE.fetching);
|
|
28
28
|
const expires = localStorage.getItem(options.expiresTokenStorageName);
|
|
29
29
|
let token;
|
|
30
30
|
if (!expires || Number.isNaN(+expires) || Date.now() > +expires) {
|
|
31
|
-
|
|
31
|
+
OAUTH_STATE.fetching = true;
|
|
32
32
|
await getOauthTokenFromOtherWindow({
|
|
33
33
|
onlyRefreshTokenWindowQueryName: options.onlyRefreshTokenWindowQueryName,
|
|
34
34
|
onWindowOpenError: options.onWindowOpenError,
|
|
@@ -43,7 +43,7 @@ const generateOauthMiddleware = (options) => async (request) => {
|
|
|
43
43
|
localStorage.setItem(options.tokenStorageName, token);
|
|
44
44
|
}
|
|
45
45
|
}
|
|
46
|
-
|
|
46
|
+
OAUTH_STATE.fetching = false;
|
|
47
47
|
}
|
|
48
48
|
if (!isSameOrigin && token)
|
|
49
49
|
request.headers = {
|
|
@@ -52,5 +52,5 @@ const generateOauthMiddleware = (options) => async (request) => {
|
|
|
52
52
|
};
|
|
53
53
|
};
|
|
54
54
|
|
|
55
|
-
export {
|
|
56
|
-
//# sourceMappingURL=oauth-
|
|
55
|
+
export { oauthBeforeHandler };
|
|
56
|
+
//# sourceMappingURL=oauth-before-handler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth-before-handler.js","sources":["../../../../src/api/before/oauth-before-handler.ts"],"sourcesContent":["import { startWith, waitUntil } from \"../../lib/utils\";\nimport { OAUTH_STATE } from \"../api.constants\";\nimport type { BeforeHandler, OauthOptions } from \"../api.types\";\nimport { getOauthTokenFromOtherWindow } from \"../oauth\";\n\nexport const oauthBeforeHandler =\n (options: OauthOptions): BeforeHandler =>\n async (request) => {\n if (!options.expiresTokenStorageName) {\n throw new Error(\"Auth middleware hasn't required options\");\n }\n\n const isSameOrigin = !startWith(request.path, \"http\");\n\n if (request.token) {\n if (!isSameOrigin)\n request.headers = {\n ...request.headers,\n Authorization: `Bearer ${request.token}`,\n };\n\n return;\n }\n\n if (OAUTH_STATE.fetching) await waitUntil(() => OAUTH_STATE.fetching);\n\n const expires = localStorage.getItem(options.expiresTokenStorageName);\n let token: string | undefined | null;\n if (!expires || Number.isNaN(+expires) || Date.now() > +expires) {\n OAUTH_STATE.fetching = true;\n await getOauthTokenFromOtherWindow({\n onlyRefreshTokenWindowQueryName: options.onlyRefreshTokenWindowQueryName,\n onWindowOpenError: options.onWindowOpenError,\n refreshTokenWindowUrl: options.refreshTokenWindowUrl,\n wait: options.wait,\n expiresTokenStorageName: options.expiresTokenStorageName,\n closeObserveInterval: options.closeObserveInterval,\n });\n if (options.tokenRequest) {\n token = await options.tokenRequest();\n if (token != undefined && options.tokenStorageName) {\n localStorage.setItem(options.tokenStorageName, token);\n }\n }\n OAUTH_STATE.fetching = false;\n }\n\n if (!isSameOrigin && token)\n request.headers = {\n ...request.headers,\n Authorization: `Bearer ${token}`,\n };\n };\n"],"names":[],"mappings":";;;;;;;;;;;;AAKO,MAAM,kBAAkB,GAC7B,CAAC,OAAqB,KACtB,OAAO,OAAO,KAAI;AAChB,IAAA,IAAI,CAAC,OAAO,CAAC,uBAAuB,EAAE;AACpC,QAAA,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC;;IAG5D,MAAM,YAAY,GAAG,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;AAErD,IAAA,I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