@sevtech/kit 20.3.2 → 21.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/browser/index.d.ts +14 -14
- package/fesm2022/browser.mjs +2 -2
- package/fesm2022/browser.mjs.map +1 -1
- package/fesm2022/environments.mjs +1 -1
- package/fesm2022/environments.mjs.map +1 -1
- package/fesm2022/http.mjs +942 -654
- package/fesm2022/http.mjs.map +1 -1
- package/fesm2022/localization.mjs +3 -8
- package/fesm2022/localization.mjs.map +1 -1
- package/fesm2022/misc.mjs +42 -20
- package/fesm2022/misc.mjs.map +1 -1
- package/fesm2022/ng-misc.mjs +46 -3
- package/fesm2022/ng-misc.mjs.map +1 -1
- package/fesm2022/sevtech-kit.mjs.map +1 -1
- package/fesm2022/ui-yoda.mjs +3 -7
- package/fesm2022/ui-yoda.mjs.map +1 -1
- package/fesm2022/ui.mjs +2 -4
- package/fesm2022/ui.mjs.map +1 -1
- package/http/index.d.ts +605 -379
- package/misc/index.d.ts +41 -12
- package/ng-misc/index.d.ts +31 -3
- package/package.json +7 -7
package/fesm2022/http.mjs
CHANGED
|
@@ -1,8 +1,31 @@
|
|
|
1
|
-
import { isArray, isNonEmptyString, isPlainObject, isNil, isString, isNumber, isBoolean, isUndefined, isFunction, isInstance, objectKeys, resolveMaybeFn, isDefined, objectEntries, randomArrayItem } from '@sevtech/kit/misc';
|
|
2
|
-
import { HttpStatusCode, HttpClient, HttpParams, HttpContext, HttpContextToken, HttpHeaders, HttpResponse, HttpEventType, HttpErrorResponse } from '@angular/common/http';
|
|
3
1
|
import * as i0 from '@angular/core';
|
|
4
2
|
import { InjectionToken, inject, Injectable, makeEnvironmentProviders, signal, computed } from '@angular/core';
|
|
5
|
-
import {
|
|
3
|
+
import { HttpClient, HttpParams, HttpContext, HttpContextToken, HttpResponseBase, HttpHeaders, HttpResponse, HttpEventType, HttpErrorResponse } from '@angular/common/http';
|
|
4
|
+
import { isArray, isString, isNumber, isBoolean, isUndefined, isFunction, isNil, isInstance, isPlainObject, objectKeys, resolveMaybeFn, isDefined, objectEntries, randomArrayItem, toArray, isNonEmptyString, isNonEmptyArray } from '@sevtech/kit/misc';
|
|
5
|
+
import { defineKitFeature, resolveConfigProviders, collectFeatureProviders } from '@sevtech/kit/ng-misc';
|
|
6
|
+
import { finalize, tap, catchError, throwError, timer, switchMap, of, delay, map, retry } from 'rxjs';
|
|
7
|
+
|
|
8
|
+
const DEFAULT_API_OPTIONS = {
|
|
9
|
+
observe: 'body',
|
|
10
|
+
contentType: 'default',
|
|
11
|
+
responseType: 'json',
|
|
12
|
+
};
|
|
13
|
+
const DEFAULT_SERIALIZE_CONFIG = {
|
|
14
|
+
arrayKeyStyle: 'plain',
|
|
15
|
+
arrayFormat: 'repeat',
|
|
16
|
+
unsupported: 'error',
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const API_PREFIX = new InjectionToken('[URL_PREFIX]: добавляет базовый префикс к URL запроса');
|
|
20
|
+
const API_OPTIONS = new InjectionToken('[API_OPTIONS]: определяет настройки запросов по умолчанию', {
|
|
21
|
+
providedIn: 'root',
|
|
22
|
+
factory: () => DEFAULT_API_OPTIONS,
|
|
23
|
+
});
|
|
24
|
+
const API_BODY_TRANSFORM = new InjectionToken('[API_BODY_TRANSFORM]: предоставляет функции для трансформации тела запроса');
|
|
25
|
+
const API_SERIALIZE = new InjectionToken('[API_SERIALIZE]: конфигурация сериализации параметров и тела запроса', {
|
|
26
|
+
providedIn: 'root',
|
|
27
|
+
factory: () => DEFAULT_SERIALIZE_CONFIG,
|
|
28
|
+
});
|
|
6
29
|
|
|
7
30
|
function parseHttpHeaders(headers) {
|
|
8
31
|
const requestHeaders = {};
|
|
@@ -14,277 +37,31 @@ function parseHttpHeaders(headers) {
|
|
|
14
37
|
}
|
|
15
38
|
return requestHeaders;
|
|
16
39
|
}
|
|
17
|
-
function resolveErrorMessage(error) {
|
|
18
|
-
try {
|
|
19
|
-
const message = resolveMessage(error);
|
|
20
|
-
return isNonEmptyString(message) ? message : undefined;
|
|
21
|
-
}
|
|
22
|
-
catch {
|
|
23
|
-
return isPlainObject(error) && isNonEmptyString(error['message'])
|
|
24
|
-
? error['message']
|
|
25
|
-
: undefined;
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
function resolveMessage(data) {
|
|
29
|
-
const errors = resolveErrorsArray(data);
|
|
30
|
-
if (isNil(errors) || errors.length === 0)
|
|
31
|
-
return data.message;
|
|
32
|
-
const foundError = errors.find((item) => isNonEmptyString(item.message));
|
|
33
|
-
return foundError?.message ? foundError.message : data.message;
|
|
34
|
-
}
|
|
35
|
-
function resolveErrorsArray(data) {
|
|
36
|
-
if (!isPlainObject(data))
|
|
37
|
-
return undefined;
|
|
38
|
-
if (isArray(data.errors))
|
|
39
|
-
return data.errors;
|
|
40
|
-
return 'error' in data && isPlainObject(data.error) ? data.error.errors : undefined;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
var ApiErrorKind;
|
|
44
|
-
(function (ApiErrorKind) {
|
|
45
|
-
/**
|
|
46
|
-
* Сетевая ошибка.
|
|
47
|
-
* @description Например, недоступен сервер, обрыв соединения, DNS‑ошибка и т.п.
|
|
48
|
-
* Может не иметь валидного HTTP‑статуса.
|
|
49
|
-
*/
|
|
50
|
-
ApiErrorKind[ApiErrorKind["Network"] = 0] = "Network";
|
|
51
|
-
/**
|
|
52
|
-
* Попытка обращения к несуществующим данным.
|
|
53
|
-
* @description Пример: отсутствует запись с указанным идентификатором.
|
|
54
|
-
* Обычно соответствует HTTP‑статусу `404 Not Found`.
|
|
55
|
-
*/
|
|
56
|
-
ApiErrorKind[ApiErrorKind["NotExist"] = 1] = "NotExist";
|
|
57
|
-
/**
|
|
58
|
-
* Ошибка валидации входных данных.
|
|
59
|
-
* @description Переданные параметры не соответствуют требованиям API.
|
|
60
|
-
* Обычно соответствует HTTP‑статусу `400 Bad Request`.
|
|
61
|
-
*/
|
|
62
|
-
ApiErrorKind[ApiErrorKind["Validation"] = 2] = "Validation";
|
|
63
|
-
/**
|
|
64
|
-
* Ошибка доступа (недостаточно прав).
|
|
65
|
-
* @description У пользователя нет прав на выполнение операции.
|
|
66
|
-
* Обычно соответствует HTTP‑статусу `403 Forbidden`.
|
|
67
|
-
*/
|
|
68
|
-
ApiErrorKind[ApiErrorKind["Access"] = 3] = "Access";
|
|
69
|
-
/**
|
|
70
|
-
* Бизнес‑ошибка, возвращаемая доменным слоем/БД.
|
|
71
|
-
* @description Например, попытка создать дубликат сущности или нарушение бизнес‑правил.
|
|
72
|
-
* В типичном случае мапится на `418 I'm a teapot`
|
|
73
|
-
*/
|
|
74
|
-
ApiErrorKind[ApiErrorKind["Domain"] = 4] = "Domain";
|
|
75
|
-
/**
|
|
76
|
-
* Таймаут запроса на стороне клиента.
|
|
77
|
-
* @description Превышено допустимое время ожидания ответа сервера.
|
|
78
|
-
* Обычно соответствует HTTP‑статусу `408 Request Timeout`.
|
|
79
|
-
*/
|
|
80
|
-
ApiErrorKind[ApiErrorKind["Timeout"] = 5] = "Timeout";
|
|
81
|
-
/**
|
|
82
|
-
* Пользователь не аутентифицирован.
|
|
83
|
-
* @description Например, отсутствует или истёк токен доступа.
|
|
84
|
-
* Обычно соответствует HTTP‑статусу `401 Unauthorized`.
|
|
85
|
-
*/
|
|
86
|
-
ApiErrorKind[ApiErrorKind["Unauthorized"] = 6] = "Unauthorized";
|
|
87
|
-
/**
|
|
88
|
-
* Неизвестная ошибка.
|
|
89
|
-
* @description Используется для любых ошибок, которые не подпадают
|
|
90
|
-
* под остальные категории.
|
|
91
|
-
*/
|
|
92
|
-
ApiErrorKind[ApiErrorKind["Unknown"] = 7] = "Unknown";
|
|
93
|
-
})(ApiErrorKind || (ApiErrorKind = {}));
|
|
94
|
-
|
|
95
|
-
class HttpBaseError {
|
|
96
|
-
constructor(httpError, resolveMessage) {
|
|
97
|
-
this.url = httpError.url;
|
|
98
|
-
this.status = httpError.status;
|
|
99
|
-
this.redirected = httpError.redirected;
|
|
100
|
-
this.payload = httpError.error;
|
|
101
|
-
this.message = resolveMessage
|
|
102
|
-
? (resolveErrorMessage(httpError.error) ?? httpError.message)
|
|
103
|
-
: httpError.message;
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
class HttpNetworkError extends HttpBaseError {
|
|
107
|
-
constructor(httpError, message) {
|
|
108
|
-
super(httpError, false);
|
|
109
|
-
this.name = HttpNetworkError.name;
|
|
110
|
-
this.kind = ApiErrorKind.Network;
|
|
111
|
-
if (isString(message)) {
|
|
112
|
-
this.message = message;
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
class HttpNotExistError extends HttpBaseError {
|
|
117
|
-
constructor(httpError) {
|
|
118
|
-
super(httpError, true);
|
|
119
|
-
this.name = HttpNotExistError.name;
|
|
120
|
-
this.kind = ApiErrorKind.NotExist;
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
class HttpValidationError extends HttpBaseError {
|
|
124
|
-
constructor(httpError) {
|
|
125
|
-
super(httpError, false);
|
|
126
|
-
this.name = HttpValidationError.name;
|
|
127
|
-
this.kind = ApiErrorKind.Validation;
|
|
128
|
-
this.errorsMap = new Map();
|
|
129
|
-
this.fillErrorsMap(httpError.error);
|
|
130
|
-
this.errors = [...this.errorsMap.values()].flat();
|
|
131
|
-
}
|
|
132
|
-
selectErrors(location) {
|
|
133
|
-
const locations = isArray(location) ? location : [location];
|
|
134
|
-
const result = [];
|
|
135
|
-
for (const key of locations) {
|
|
136
|
-
result.push(...(this.errorsMap.get(key) ?? []));
|
|
137
|
-
}
|
|
138
|
-
return result;
|
|
139
|
-
}
|
|
140
|
-
resolveMessages(location, separator = null) {
|
|
141
|
-
const errors = this.selectErrors(location);
|
|
142
|
-
const messages = errors.map((error) => error.message);
|
|
143
|
-
if (messages.length === 0)
|
|
144
|
-
return '';
|
|
145
|
-
return isNil(separator) ? messages[0] : messages.join(separator);
|
|
146
|
-
}
|
|
147
|
-
fillErrorsMap(data) {
|
|
148
|
-
if (isNil(data))
|
|
149
|
-
return;
|
|
150
|
-
const errors = resolveErrorsArray(data);
|
|
151
|
-
if (isNil(errors))
|
|
152
|
-
return;
|
|
153
|
-
for (const error of errors) {
|
|
154
|
-
const item = this.normalizeValidationItem(error);
|
|
155
|
-
if (isNil(item))
|
|
156
|
-
continue;
|
|
157
|
-
this.errorsMap.set(item.location, [...(this.errorsMap.get(item.location) ?? []), item]);
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
normalizeValidationItem(item) {
|
|
161
|
-
if (isValidationItem(item)) {
|
|
162
|
-
const path = item.path.replace(/[\\/]+/g, '.').replace(/^\./, '');
|
|
163
|
-
return { ...item, path };
|
|
164
|
-
}
|
|
165
|
-
if (!isString(item.path) || !isString(item.message))
|
|
166
|
-
return null;
|
|
167
|
-
const [location, ...rest] = item.path.split(/[\\/]/);
|
|
168
|
-
if (!isValidationLocations(location) || rest.length === 0)
|
|
169
|
-
return null;
|
|
170
|
-
return {
|
|
171
|
-
location,
|
|
172
|
-
message: item.message,
|
|
173
|
-
path: rest.join('.'),
|
|
174
|
-
};
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
class HttpAccessError extends HttpBaseError {
|
|
178
|
-
constructor(httpError) {
|
|
179
|
-
super(httpError, true);
|
|
180
|
-
this.name = HttpAccessError.name;
|
|
181
|
-
this.kind = ApiErrorKind.Access;
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
class HttpDomainError extends HttpBaseError {
|
|
185
|
-
constructor(httpError) {
|
|
186
|
-
super(httpError, true);
|
|
187
|
-
this.name = HttpDomainError.name;
|
|
188
|
-
this.kind = ApiErrorKind.Domain;
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
class HttpTimeoutError extends HttpBaseError {
|
|
192
|
-
constructor(httpError) {
|
|
193
|
-
super(httpError, true);
|
|
194
|
-
this.name = HttpTimeoutError.name;
|
|
195
|
-
this.kind = ApiErrorKind.Timeout;
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
class HttpUnauthorizedError extends HttpBaseError {
|
|
199
|
-
constructor(httpError) {
|
|
200
|
-
super(httpError, true);
|
|
201
|
-
this.name = HttpUnauthorizedError.name;
|
|
202
|
-
this.kind = ApiErrorKind.Unauthorized;
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
class HttpUnknownError extends HttpBaseError {
|
|
206
|
-
constructor(httpError) {
|
|
207
|
-
super(httpError, true);
|
|
208
|
-
this.name = HttpUnknownError.name;
|
|
209
|
-
this.kind = ApiErrorKind.Unknown;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
40
|
|
|
213
|
-
function isValidationLocations(data) {
|
|
214
|
-
return isString(data) && ['body', 'header', 'path', 'env', 'query'].includes(data);
|
|
215
|
-
}
|
|
216
|
-
function isBaseError(data) {
|
|
217
|
-
if (!isPlainObject(data))
|
|
218
|
-
return false;
|
|
219
|
-
if (data['success'] !== false || !isString(data['message'])) {
|
|
220
|
-
return false;
|
|
221
|
-
}
|
|
222
|
-
const errors = resolveErrorsArray(data);
|
|
223
|
-
if (isNil(errors))
|
|
224
|
-
return true;
|
|
225
|
-
return errors.every(isDBErrorItem);
|
|
226
|
-
}
|
|
227
|
-
function isValidationError(data) {
|
|
228
|
-
if (!isPlainObject(data))
|
|
229
|
-
return false;
|
|
230
|
-
if (data['status'] !== HttpStatusCode.BadRequest)
|
|
231
|
-
return false;
|
|
232
|
-
return isArray(data['errors']) && data['errors'].every(isValidationItem);
|
|
233
|
-
}
|
|
234
|
-
function isDBErrorItem(data) {
|
|
235
|
-
return isPlainObject(data) && isString(data['code']);
|
|
236
|
-
}
|
|
237
|
-
function isValidationItem(data) {
|
|
238
|
-
return (isPlainObject(data) &&
|
|
239
|
-
isString(data['path']) &&
|
|
240
|
-
isString(data['message']) &&
|
|
241
|
-
isString(data['location']));
|
|
242
|
-
}
|
|
243
41
|
function isPrimitive(data) {
|
|
244
42
|
return isString(data) || isNumber(data) || isBoolean(data);
|
|
245
43
|
}
|
|
246
|
-
function isApiError(data, kind) {
|
|
247
|
-
if (data instanceof HttpBaseError) {
|
|
248
|
-
return isNil(kind) ? true : data.kind === kind;
|
|
249
|
-
}
|
|
250
|
-
return false;
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
const DEFAULT_API_OPTIONS = {
|
|
254
|
-
observe: 'body',
|
|
255
|
-
contentType: 'default',
|
|
256
|
-
responseType: 'json',
|
|
257
|
-
serialize: {
|
|
258
|
-
arrayKeyStyle: 'plain',
|
|
259
|
-
arrayFormat: 'repeat',
|
|
260
|
-
unsupported: 'error',
|
|
261
|
-
},
|
|
262
|
-
};
|
|
263
|
-
|
|
264
|
-
const API_PREFIX = new InjectionToken('[URL_PREFIX]: добавляет базовый префикс к URL запроса');
|
|
265
|
-
const API_OPTIONS = new InjectionToken('[API_OPTIONS]: определяет настройки запросов по умолчанию', {
|
|
266
|
-
providedIn: 'root',
|
|
267
|
-
factory: () => DEFAULT_API_OPTIONS,
|
|
268
|
-
});
|
|
269
|
-
const API_BODY_TRANSFORM = new InjectionToken('[API_BODY_TRANSFORM]: предоставляет функции для трансформации тела запроса');
|
|
270
44
|
|
|
271
45
|
const ERROR_NAMESPACE = '[HTTP_API]';
|
|
46
|
+
const TRANSFER_CACHE_METHODS = new Set(['GET', 'HEAD', 'POST']);
|
|
47
|
+
const ABSOLUTE_URL = /^https?:\/\//i;
|
|
272
48
|
class ApiBase {
|
|
273
49
|
constructor() {
|
|
274
50
|
this.httpClient = inject(HttpClient);
|
|
275
51
|
this.bodyTransform = inject(API_BODY_TRANSFORM, { optional: true });
|
|
52
|
+
this.serialize = inject(API_SERIALIZE);
|
|
276
53
|
this.prefix = inject(API_PREFIX, { optional: true });
|
|
277
54
|
this.options = inject(API_OPTIONS);
|
|
278
55
|
}
|
|
279
56
|
request(method, url, options) {
|
|
280
57
|
const { contentType, body, serialize, ...restOptions } = this.resolveRequestOptions(options);
|
|
281
|
-
const
|
|
282
|
-
const requestParams = this.resolveOptions(restOptions,
|
|
283
|
-
const requestBody = this.resolveBody(body, contentType ?? 'default',
|
|
58
|
+
const serializeConfig = this.resolveSerializeConfig(serialize);
|
|
59
|
+
const requestParams = this.resolveOptions(restOptions, serializeConfig);
|
|
60
|
+
const requestBody = this.resolveBody(body, contentType ?? 'default', serializeConfig);
|
|
284
61
|
if (!isUndefined(requestBody)) {
|
|
285
62
|
requestParams['body'] = requestBody;
|
|
286
63
|
}
|
|
287
|
-
if (method
|
|
64
|
+
if (!TRANSFER_CACHE_METHODS.has(method)) {
|
|
288
65
|
delete requestParams['transferCache'];
|
|
289
66
|
}
|
|
290
67
|
return this.httpClient.request(method, this.resolveUrl(url), requestParams);
|
|
@@ -297,37 +74,38 @@ class ApiBase {
|
|
|
297
74
|
}
|
|
298
75
|
resolveSerializeConfig(config) {
|
|
299
76
|
return {
|
|
300
|
-
...
|
|
77
|
+
...this.serialize,
|
|
301
78
|
...config,
|
|
302
79
|
};
|
|
303
80
|
}
|
|
304
81
|
resolveBody(body, contentType, config) {
|
|
305
|
-
|
|
306
|
-
if (
|
|
307
|
-
|
|
82
|
+
let transformed = body;
|
|
83
|
+
if (isFunction(this.bodyTransform) && !isNil(body)) {
|
|
84
|
+
transformed = this.bodyTransform(body);
|
|
85
|
+
}
|
|
86
|
+
if (isNil(transformed))
|
|
87
|
+
return transformed;
|
|
308
88
|
switch (contentType) {
|
|
309
89
|
case 'encoded':
|
|
310
|
-
return normalizeEncodedContent(
|
|
90
|
+
return normalizeEncodedContent(transformed, config);
|
|
311
91
|
case 'text':
|
|
312
|
-
return normalizeTextContent(
|
|
92
|
+
return normalizeTextContent(transformed);
|
|
313
93
|
case 'form-data':
|
|
314
|
-
return normalizeFormDataContent(
|
|
94
|
+
return normalizeFormDataContent(transformed, config);
|
|
315
95
|
case 'binary':
|
|
316
|
-
return normalizeBinaryContent(
|
|
96
|
+
return normalizeBinaryContent(transformed);
|
|
317
97
|
default:
|
|
318
|
-
return
|
|
98
|
+
return transformed;
|
|
319
99
|
}
|
|
320
100
|
}
|
|
321
101
|
resolveUrl(url) {
|
|
322
|
-
if (
|
|
102
|
+
if (ABSOLUTE_URL.test(url) || isNil(this.prefix))
|
|
323
103
|
return url;
|
|
324
104
|
const normalizedPrefix = this.prefix.replace(/\/$/, '');
|
|
325
105
|
const normalizedUrl = url.replace(/^\//, '');
|
|
326
106
|
return `${normalizedPrefix}/${normalizedUrl}`;
|
|
327
107
|
}
|
|
328
108
|
resolveOptions(options, serializeConfig) {
|
|
329
|
-
if (isNil(options))
|
|
330
|
-
return {};
|
|
331
109
|
const params = normalizeParams(options.params, serializeConfig);
|
|
332
110
|
const context = normalizeContext(options.context);
|
|
333
111
|
return {
|
|
@@ -395,7 +173,7 @@ function normalizeParamsObject(obj, config, safeBlob) {
|
|
|
395
173
|
return objectKeys(obj).reduce((result, key) => {
|
|
396
174
|
try {
|
|
397
175
|
const value = normalizeValue(obj[key], config, safeBlob);
|
|
398
|
-
if (
|
|
176
|
+
if (isUndefined(value))
|
|
399
177
|
return result;
|
|
400
178
|
const paramKey = config.arrayKeyStyle === 'brackets' && isArray(value) ? `${key}[]` : key;
|
|
401
179
|
result[paramKey] = isArray(value) && config.arrayFormat === 'comma' ? String(value) : value;
|
|
@@ -414,13 +192,15 @@ function normalizeValue(value, config, safeBlob) {
|
|
|
414
192
|
return;
|
|
415
193
|
if (isPrimitive(value))
|
|
416
194
|
return String(value);
|
|
195
|
+
if (isInstance(value, Date))
|
|
196
|
+
return normalizeDate(value, config);
|
|
417
197
|
if (isArray(value))
|
|
418
|
-
return normalizeArray(value, config
|
|
198
|
+
return normalizeArray(value, config, safeBlob);
|
|
419
199
|
if (safeBlob && value instanceof Blob)
|
|
420
200
|
return value;
|
|
421
201
|
return handleUnsupported(value, config.unsupported);
|
|
422
202
|
}
|
|
423
|
-
function normalizeArray(values,
|
|
203
|
+
function normalizeArray(values, config, safeBlob) {
|
|
424
204
|
const result = [];
|
|
425
205
|
for (const value of values) {
|
|
426
206
|
if (isNil(value))
|
|
@@ -433,15 +213,23 @@ function normalizeArray(values, unsupported, safeBlob) {
|
|
|
433
213
|
result.push(value);
|
|
434
214
|
continue;
|
|
435
215
|
}
|
|
436
|
-
const data =
|
|
216
|
+
const data = isInstance(value, Date)
|
|
217
|
+
? normalizeDate(value, config)
|
|
218
|
+
: handleUnsupported(value, config.unsupported);
|
|
437
219
|
if (isString(data)) {
|
|
438
220
|
result.push(data);
|
|
439
221
|
}
|
|
440
222
|
}
|
|
441
223
|
return result.length > 0 ? result : undefined;
|
|
442
224
|
}
|
|
443
|
-
function
|
|
444
|
-
|
|
225
|
+
function normalizeDate(value, config) {
|
|
226
|
+
if (!isFunction(config.date))
|
|
227
|
+
return handleUnsupported(value, config.unsupported);
|
|
228
|
+
const result = config.date(value);
|
|
229
|
+
return isNil(result) ? undefined : String(result);
|
|
230
|
+
}
|
|
231
|
+
function handleUnsupported(value, strategy) {
|
|
232
|
+
switch (strategy) {
|
|
445
233
|
case 'stringify':
|
|
446
234
|
return JSON.stringify(value);
|
|
447
235
|
case 'skip':
|
|
@@ -451,6 +239,20 @@ function handleUnsupported(value, unsupportedStrategy) {
|
|
|
451
239
|
}
|
|
452
240
|
}
|
|
453
241
|
|
|
242
|
+
/**
|
|
243
|
+
* Типизированная обёртка над `HttpClient`: подставляет префикс из `withPrefix`,
|
|
244
|
+
* сериализует query-параметры и тело, возвращает типизированный поток.
|
|
245
|
+
* @description У `get` и `delete` второй аргумент - query-параметры,
|
|
246
|
+
* у `post`, `put` и `patch` - тело запроса. Третий везде - опции запроса.
|
|
247
|
+
*
|
|
248
|
+
* Тип результата выводится из `observe` и `responseType`.
|
|
249
|
+
* @example
|
|
250
|
+
* private readonly http = inject(HttpApiService);
|
|
251
|
+
*
|
|
252
|
+
* this.http.get<User[]>('/users', { page: 1 });
|
|
253
|
+
* this.http.post<User>('/users', { name: 'Иван' });
|
|
254
|
+
* this.http.get('/report', null, { responseType: 'blob' });
|
|
255
|
+
*/
|
|
454
256
|
class HttpApiService extends ApiBase {
|
|
455
257
|
get(url, params, options) {
|
|
456
258
|
return this.request('GET', url, { ...options, params });
|
|
@@ -477,98 +279,95 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.18", ngImpo
|
|
|
477
279
|
}]
|
|
478
280
|
}] });
|
|
479
281
|
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
282
|
+
/**
|
|
283
|
+
* Добавляет базовый префикс к относительным URL запросов.
|
|
284
|
+
* @description Абсолютные адреса (`http://`, `https://`) остаются без изменений.
|
|
285
|
+
* Лишние слэши на стыке убираются. `null` отключает префикс.
|
|
286
|
+
*
|
|
287
|
+
* Фабрика вызывается один раз в контексте инъекции - внутри доступен `inject()`
|
|
288
|
+
* @example
|
|
289
|
+
* provideHttpApi(withPrefix('https://api.example.com/v1'));
|
|
290
|
+
* @example
|
|
291
|
+
* provideHttpApi(withPrefix(() => inject(ENVIRONMENT).apiUrl));
|
|
292
|
+
*/
|
|
293
|
+
const withPrefix = defineKitFeature(0 /* FeatureKind.Prefix */, (prefix) => ({
|
|
294
|
+
provide: API_PREFIX,
|
|
295
|
+
useFactory: () => resolveMaybeFn(prefix),
|
|
296
|
+
}));
|
|
297
|
+
/**
|
|
298
|
+
* Преобразует тело запроса перед сериализацией.
|
|
299
|
+
* @description Применяется до обработки `contentType`, поэтому получает тело
|
|
300
|
+
* в исходном виде. Для запросов без тела (`GET`, `DELETE`) не вызывается.
|
|
301
|
+
* @example
|
|
302
|
+
* provideHttpApi({}, withBodyTransform(snakeCaseKeys));
|
|
303
|
+
*/
|
|
304
|
+
const withBodyTransform = defineKitFeature(1 /* FeatureKind.BodyTransform */, (transform) => ({
|
|
305
|
+
provide: API_BODY_TRANSFORM,
|
|
306
|
+
useValue: transform,
|
|
307
|
+
}));
|
|
308
|
+
/**
|
|
309
|
+
* Задаёт правила сериализации query-параметров и тела по умолчанию.
|
|
310
|
+
* @description Переопределяется на уровне запроса через `options.serialize`,
|
|
311
|
+
* незаданные поля берутся отсюда.
|
|
312
|
+
*
|
|
313
|
+
* Фабрика вызывается один раз в контексте инъекции - внутри доступен `inject()`
|
|
314
|
+
* @example
|
|
315
|
+
* provideHttpApi(
|
|
316
|
+
* withSerializeConfig({ arrayKeyStyle: 'brackets', date: (value) => value.toISOString() }),
|
|
317
|
+
* );
|
|
318
|
+
*/
|
|
319
|
+
const withSerializeConfig = defineKitFeature(2 /* FeatureKind.Serialize */, (config) => ({
|
|
320
|
+
provide: API_SERIALIZE,
|
|
321
|
+
useFactory: () => ({ ...DEFAULT_SERIALIZE_CONFIG, ...resolveMaybeFn(config) }),
|
|
322
|
+
}));
|
|
502
323
|
function provideHttpApi(options, ...features) {
|
|
503
|
-
|
|
324
|
+
const providers = resolveConfigProviders(options, (item) => [
|
|
504
325
|
{
|
|
505
326
|
provide: API_OPTIONS,
|
|
506
327
|
useFactory: () => {
|
|
507
|
-
|
|
508
|
-
return DEFAULT_API_OPTIONS;
|
|
509
|
-
const resolvedOptions = resolveMaybeFn(options);
|
|
328
|
+
const resolvedOptions = resolveMaybeFn(item);
|
|
510
329
|
return {
|
|
511
330
|
...DEFAULT_API_OPTIONS,
|
|
512
331
|
...resolvedOptions,
|
|
513
332
|
};
|
|
514
333
|
},
|
|
515
334
|
},
|
|
516
|
-
...[options, ...features]
|
|
517
|
-
.filter((feature) => 'kind' in feature)
|
|
518
|
-
.flatMap((feature) => feature.providers),
|
|
519
335
|
]);
|
|
520
|
-
|
|
521
|
-
/**
|
|
522
|
-
* @deprecated use provideHttpApi({}, withPrefix())
|
|
523
|
-
*/
|
|
524
|
-
function provideApiPrefix(prefix) {
|
|
525
|
-
return withPrefix(prefix).providers;
|
|
526
|
-
}
|
|
527
|
-
/**
|
|
528
|
-
* @deprecated use provideHttpApi({}, withBodyTransform())
|
|
529
|
-
*/
|
|
530
|
-
function provideApiBodyTransform(transform) {
|
|
531
|
-
return withBodyTransform(transform).providers;
|
|
532
|
-
}
|
|
533
|
-
/**
|
|
534
|
-
* @deprecated use provideHttpApi()
|
|
535
|
-
*/
|
|
536
|
-
function provideApiOptions(options) {
|
|
537
|
-
return {
|
|
538
|
-
provide: API_OPTIONS,
|
|
539
|
-
useFactory: () => {
|
|
540
|
-
const resolvedOptions = resolveMaybeFn(options);
|
|
541
|
-
return {
|
|
542
|
-
...DEFAULT_API_OPTIONS,
|
|
543
|
-
...resolvedOptions,
|
|
544
|
-
};
|
|
545
|
-
},
|
|
546
|
-
};
|
|
336
|
+
return makeEnvironmentProviders([...providers, ...collectFeatureProviders(options, ...features)]);
|
|
547
337
|
}
|
|
548
338
|
|
|
549
339
|
const DEFAULT_PROGRESS_CONFIG = {
|
|
550
|
-
|
|
340
|
+
filter: [],
|
|
551
341
|
enabled: true,
|
|
552
342
|
};
|
|
553
343
|
|
|
554
|
-
const PROGRESS_CONFIG = new InjectionToken('PROGRESS_CONFIG', {
|
|
344
|
+
const PROGRESS_CONFIG = new InjectionToken('[PROGRESS_CONFIG]: конфигурация progress-интерсептора', {
|
|
345
|
+
providedIn: 'root',
|
|
555
346
|
factory: () => DEFAULT_PROGRESS_CONFIG,
|
|
556
347
|
});
|
|
557
348
|
/**
|
|
558
|
-
*
|
|
349
|
+
* Управление прогрессом конкретного запроса.
|
|
559
350
|
*
|
|
560
351
|
* @description
|
|
561
352
|
* Поведение:
|
|
562
|
-
* - `true` - включить глобальный прогресс (игнорирует
|
|
353
|
+
* - `true` - включить глобальный прогресс (игнорирует `filter`)
|
|
354
|
+
* - `false` - не учитывать запрос в прогрессе
|
|
563
355
|
* - `string` - использовать локальный ключ
|
|
564
|
-
* - `null` - стандартное поведение (учитывает
|
|
356
|
+
* - `null` - стандартное поведение (учитывает `filter`)
|
|
565
357
|
* @example
|
|
566
|
-
*
|
|
567
|
-
* context:
|
|
358
|
+
* api.get('/users', null, {
|
|
359
|
+
* context: (ctx) => ctx.set(USE_PROGRESS, 'users-table'),
|
|
568
360
|
* });
|
|
569
361
|
* @default null
|
|
570
362
|
*/
|
|
571
363
|
const USE_PROGRESS = new HttpContextToken(() => null);
|
|
364
|
+
/**
|
|
365
|
+
* Настраивает `progressInterceptor`.
|
|
366
|
+
* @description Состояние читается через `ProgressHttpService`. Точечно
|
|
367
|
+
* управляется контекстом `USE_PROGRESS`, в том числе локальными ключами.
|
|
368
|
+
* @example
|
|
369
|
+
* provideProgressConfig({ filter: ['/api/config', /\/health$/] });
|
|
370
|
+
*/
|
|
572
371
|
function provideProgressConfig(config) {
|
|
573
372
|
return makeEnvironmentProviders([
|
|
574
373
|
{
|
|
@@ -652,14 +451,54 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.18", ngImpo
|
|
|
652
451
|
}]
|
|
653
452
|
}] });
|
|
654
453
|
|
|
454
|
+
function matchRequest(request, filter) {
|
|
455
|
+
return matchesFilter(request, filter);
|
|
456
|
+
}
|
|
457
|
+
function matchResponse(request, response, filter) {
|
|
458
|
+
const status = response instanceof HttpResponseBase ? response.status : undefined;
|
|
459
|
+
return matchesFilter(request, filter, status);
|
|
460
|
+
}
|
|
461
|
+
function matchesFilter(request, filter, status) {
|
|
462
|
+
if (isArray(filter)) {
|
|
463
|
+
return filter.some((item) => matchesFilter(request, item, status));
|
|
464
|
+
}
|
|
465
|
+
if (isString(filter) || filter instanceof RegExp) {
|
|
466
|
+
return matchesUrl(request.url, filter);
|
|
467
|
+
}
|
|
468
|
+
if (isNil(filter.method) && isNil(filter.url) && isNil(filter.status))
|
|
469
|
+
return false;
|
|
470
|
+
if (isString(filter.method) && filter.method !== request.method)
|
|
471
|
+
return false;
|
|
472
|
+
if (isDefined(filter.url) && !matchesUrl(request.url, filter.url))
|
|
473
|
+
return false;
|
|
474
|
+
return isNil(filter.status) || isNil(status) || matchesStatus(status, filter.status);
|
|
475
|
+
}
|
|
476
|
+
function matchesStatus(status, filter) {
|
|
477
|
+
if (isArray(filter)) {
|
|
478
|
+
return filter.some((item) => matchesStatus(status, item));
|
|
479
|
+
}
|
|
480
|
+
return filter instanceof RegExp ? testRegExp(filter, String(status)) : filter === status;
|
|
481
|
+
}
|
|
482
|
+
function matchesUrl(url, pattern) {
|
|
483
|
+
if (isArray(pattern)) {
|
|
484
|
+
return pattern.some((item) => matchesUrl(url, item));
|
|
485
|
+
}
|
|
486
|
+
return isString(pattern) ? url.includes(pattern) : testRegExp(pattern, url);
|
|
487
|
+
}
|
|
488
|
+
function testRegExp(pattern, value) {
|
|
489
|
+
if (pattern.global || pattern.sticky) {
|
|
490
|
+
pattern.lastIndex = 0;
|
|
491
|
+
}
|
|
492
|
+
return pattern.test(value);
|
|
493
|
+
}
|
|
494
|
+
|
|
655
495
|
function resolveProgressConfig(request, config) {
|
|
656
496
|
const useProgress = request.context.get(USE_PROGRESS);
|
|
657
497
|
if (isDefined(useProgress))
|
|
658
498
|
return useProgress;
|
|
659
499
|
if (!config.enabled)
|
|
660
500
|
return false;
|
|
661
|
-
|
|
662
|
-
return !silent.some((rule) => isString(rule) ? request.url.includes(rule) : rule.test(request.url));
|
|
501
|
+
return !matchRequest(request, config.filter);
|
|
663
502
|
}
|
|
664
503
|
const progressInterceptor = (request, next) => {
|
|
665
504
|
const manager = inject(ProgressManagerService);
|
|
@@ -667,16 +506,38 @@ const progressInterceptor = (request, next) => {
|
|
|
667
506
|
if (!config)
|
|
668
507
|
return next(request);
|
|
669
508
|
const key = isString(config) ? config : undefined;
|
|
670
|
-
manager.start(
|
|
509
|
+
manager.start(key);
|
|
671
510
|
return next(request).pipe(finalize(() => manager.stop(key)));
|
|
672
511
|
};
|
|
673
512
|
|
|
674
513
|
const DEFAULT_HEADERS_CONFIG = {
|
|
675
|
-
|
|
514
|
+
filter: [],
|
|
676
515
|
enabled: true,
|
|
677
516
|
strategy: 'replace',
|
|
678
517
|
};
|
|
679
518
|
|
|
519
|
+
/**
|
|
520
|
+
* Управление применением заголовков из `withHeaders` и `withHeadersResolver`
|
|
521
|
+
* для конкретного запроса.
|
|
522
|
+
* @description Имеет приоритет над `enabled` и `filter` из конфигурации.
|
|
523
|
+
*
|
|
524
|
+
* Возможные значения:
|
|
525
|
+
* - `true` - применить заголовки, игнорируя `filter`
|
|
526
|
+
* - `false` - не применять
|
|
527
|
+
* - `null` - стандартное поведение (учитывает `enabled` и `filter`)
|
|
528
|
+
* @example
|
|
529
|
+
* api.get('/public/config', null, {
|
|
530
|
+
* context: (ctx) => ctx.set(USE_HEADERS, false),
|
|
531
|
+
* });
|
|
532
|
+
* @default null
|
|
533
|
+
*/
|
|
534
|
+
const USE_HEADERS = new HttpContextToken(() => null);
|
|
535
|
+
const HEADERS_RESOLVER = new InjectionToken('[HEADERS_RESOLVER]: предоставляет заголовок для http-запроса');
|
|
536
|
+
const HEADERS_CONFIG = new InjectionToken('[HEADERS_CONFIG]: конфигурация работы headers-интерсептора', {
|
|
537
|
+
providedIn: 'root',
|
|
538
|
+
factory: () => DEFAULT_HEADERS_CONFIG,
|
|
539
|
+
});
|
|
540
|
+
|
|
680
541
|
function applyHeaders(headers, key, value, strategy) {
|
|
681
542
|
if (strategy === 'replace')
|
|
682
543
|
return value;
|
|
@@ -687,140 +548,143 @@ function applyHeaders(headers, key, value, strategy) {
|
|
|
687
548
|
if (isNil(prev))
|
|
688
549
|
return value;
|
|
689
550
|
const nextValues = isArray(value) ? value : [value];
|
|
690
|
-
|
|
691
|
-
return [...prev, ...nextValues];
|
|
692
|
-
return [prev, ...nextValues];
|
|
551
|
+
return isArray(prev) ? [...prev, ...nextValues] : [prev, ...nextValues];
|
|
693
552
|
}
|
|
694
553
|
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
},
|
|
554
|
+
/**
|
|
555
|
+
* Добавляет статические заголовки ко всем запросам.
|
|
556
|
+
* @description Можно указывать несколько раз, значения накапливаются.
|
|
557
|
+
* Если стратегия не задана, берётся `strategy` из конфигурации.
|
|
558
|
+
*
|
|
559
|
+
* Значения фиксируются в момент регистрации, поэтому дальнейшие изменения
|
|
560
|
+
* переданного объекта на запросы не влияют.
|
|
561
|
+
* @example
|
|
562
|
+
* provideHeadersConfig(
|
|
563
|
+
* withHeaders({ 'x-app': 'erp' }),
|
|
564
|
+
* withHeaders({ 'accept-language': 'ru' }, 'skip'),
|
|
565
|
+
* );
|
|
566
|
+
*/
|
|
567
|
+
const withHeaders = defineKitFeature(0 /* FeatureKind.Headers */, (headers, strategy) => {
|
|
568
|
+
const entries = objectEntries(headers).map(([key, value]) => {
|
|
569
|
+
if (!isArray(value))
|
|
570
|
+
return [key, value];
|
|
571
|
+
const copy = [...value];
|
|
572
|
+
Object.freeze(copy);
|
|
573
|
+
return [key, copy];
|
|
574
|
+
});
|
|
575
|
+
return {
|
|
576
|
+
multi: true,
|
|
577
|
+
provide: HEADERS_RESOLVER,
|
|
578
|
+
useFactory: () => {
|
|
579
|
+
const applyStrategy = strategy ?? inject(HEADERS_CONFIG).strategy;
|
|
580
|
+
return (_, target) => {
|
|
581
|
+
for (const [key, value] of entries) {
|
|
582
|
+
target[key] = applyHeaders(target, key, value, applyStrategy ?? DEFAULT_HEADERS_CONFIG.strategy);
|
|
583
|
+
}
|
|
584
|
+
};
|
|
727
585
|
},
|
|
728
|
-
|
|
586
|
+
};
|
|
587
|
+
});
|
|
588
|
+
/**
|
|
589
|
+
* Добавляет функцию, вычисляющую заголовки на каждый запрос.
|
|
590
|
+
* @description Можно указывать несколько раз, резолверы вызываются по очереди.
|
|
591
|
+
* @example
|
|
592
|
+
* provideHeadersConfig(
|
|
593
|
+
* {},
|
|
594
|
+
* withHeadersResolver((request, headers) => {
|
|
595
|
+
* headers['authorization'] = `Bearer ${inject(AuthService).token()}`;
|
|
596
|
+
* }),
|
|
597
|
+
* );
|
|
598
|
+
*/
|
|
599
|
+
const withHeadersResolver = defineKitFeature(1 /* FeatureKind.Resolver */, (resolver) => ({
|
|
600
|
+
multi: true,
|
|
601
|
+
provide: HEADERS_RESOLVER,
|
|
602
|
+
useValue: resolver,
|
|
603
|
+
}));
|
|
604
|
+
function provideHeadersConfig(config, ...features) {
|
|
605
|
+
const providers = resolveConfigProviders(config, (item) => ({
|
|
606
|
+
provide: HEADERS_CONFIG,
|
|
607
|
+
useFactory: () => ({
|
|
608
|
+
...DEFAULT_HEADERS_CONFIG,
|
|
609
|
+
...resolveMaybeFn(item),
|
|
610
|
+
}),
|
|
611
|
+
}));
|
|
612
|
+
return makeEnvironmentProviders([...providers, ...collectFeatureProviders(config, ...features)]);
|
|
729
613
|
}
|
|
730
614
|
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
return rule.some((item) => matchesUrl(item, request.url));
|
|
615
|
+
const headersInterceptor = (request, next) => {
|
|
616
|
+
const config = inject(HEADERS_CONFIG);
|
|
617
|
+
if (!shouldApply(request, config))
|
|
618
|
+
return next(request);
|
|
619
|
+
const resolvers = inject(HEADERS_RESOLVER, { optional: true }) ?? [];
|
|
620
|
+
const requestHeaders = parseHttpHeaders(request.headers);
|
|
621
|
+
for (const resolver of resolvers) {
|
|
622
|
+
resolver(request, requestHeaders);
|
|
740
623
|
}
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
return methodOk && urlOk;
|
|
745
|
-
}
|
|
746
|
-
function canUseInterceptor(request, config) {
|
|
624
|
+
return next(request.clone({ headers: new HttpHeaders(requestHeaders) }));
|
|
625
|
+
};
|
|
626
|
+
function shouldApply(request, config) {
|
|
747
627
|
const flag = request.context.get(USE_HEADERS);
|
|
748
628
|
if (isDefined(flag))
|
|
749
629
|
return flag;
|
|
750
630
|
if (!config.enabled)
|
|
751
631
|
return false;
|
|
752
|
-
return !
|
|
632
|
+
return !matchRequest(request, config.filter);
|
|
753
633
|
}
|
|
754
|
-
const headersInterceptor = (request, next) => {
|
|
755
|
-
const config = inject(HEADERS_CONFIG);
|
|
756
|
-
if (!canUseInterceptor(request, config))
|
|
757
|
-
return next(request);
|
|
758
|
-
const resolvers = inject(HEADERS_RESOLVER, { optional: true }) ?? [];
|
|
759
|
-
const requestHeaders = parseHttpHeaders(request.headers);
|
|
760
|
-
const headersMap = resolvers.reduce((headers, resolver) => resolver(request, headers) || headers, requestHeaders);
|
|
761
|
-
return next(request.clone({ headers: new HttpHeaders(headersMap) }));
|
|
762
|
-
};
|
|
763
634
|
|
|
764
|
-
const
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
duration: (duration) => {
|
|
780
|
-
return duration >= 1000 ? 'color: #DD2A2A; font-weight: bold;' : 'color: #18BC36;';
|
|
781
|
-
},
|
|
782
|
-
status: {
|
|
783
|
-
success: `${DEFAULT_STATUS_STYLE} color: #18BC36; background: #18BC3626;`,
|
|
784
|
-
redirect: `${DEFAULT_STATUS_STYLE} color: #1863DF; background: #1863DF26;`,
|
|
785
|
-
clientError: `${DEFAULT_STATUS_STYLE} color: #FFA000; background: #FFA00026;`,
|
|
786
|
-
serverError: `${DEFAULT_STATUS_STYLE} color: #DD2A2A; background: #DD2A2A26;`,
|
|
787
|
-
network: `${DEFAULT_STATUS_STYLE} color: #9CA3AF; background: #9CA3AF26;`,
|
|
788
|
-
},
|
|
789
|
-
method: {
|
|
790
|
-
GET: `${DEFAULT_METHOD_STYLE} background-color: #61affe;`,
|
|
791
|
-
POST: `${DEFAULT_METHOD_STYLE} background-color: #49cc90;`,
|
|
792
|
-
PUT: `${DEFAULT_METHOD_STYLE} background-color: #fca130;`,
|
|
793
|
-
PATCH: `${DEFAULT_METHOD_STYLE} background-color: #50e3c2;`,
|
|
794
|
-
DELETE: `${DEFAULT_METHOD_STYLE} background-color: #f93e3e;`,
|
|
795
|
-
OPTIONS: `${DEFAULT_METHOD_STYLE} background-color: #0d5aa7;`,
|
|
796
|
-
HEAD: `${DEFAULT_METHOD_STYLE} background-color: #9012fe;`,
|
|
797
|
-
},
|
|
635
|
+
const METHOD_COLORS = {
|
|
636
|
+
GET: '#61AFFE',
|
|
637
|
+
POST: '#49CC90',
|
|
638
|
+
PUT: '#FCA130',
|
|
639
|
+
PATCH: '#50E3C2',
|
|
640
|
+
DELETE: '#F93E3E',
|
|
641
|
+
OPTIONS: '#0D5AA7',
|
|
642
|
+
HEAD: '#9012FE',
|
|
643
|
+
};
|
|
644
|
+
const STATUS_COLORS = {
|
|
645
|
+
success: '#18BC36',
|
|
646
|
+
redirect: '#1863DF',
|
|
647
|
+
clientError: '#FFA000',
|
|
648
|
+
serverError: '#DD2A2A',
|
|
649
|
+
network: '#9CA3AF',
|
|
798
650
|
};
|
|
651
|
+
const ALPHA = '26';
|
|
652
|
+
const UNKNOWN_COLOR = '#9CA3AF';
|
|
653
|
+
const FALLBACK_ORIGIN = 'http://localhost';
|
|
654
|
+
const TITLE_STYLE = 'font-weight: 700; margin-top: 10px; color: #6B7280';
|
|
655
|
+
const NAMESPACE_STYLE = 'font-size: 0; padding: 0; margin: 0';
|
|
656
|
+
const methodStyle = (color) => `font-weight: 700; padding: 2px 4px; border-radius: 4px 0 0 4px; color: #fff; background-color: ${color};`;
|
|
657
|
+
const hrefStyle = (color) => `padding: 2px 4px; border-radius: 0 4px 4px 0; background-color: ${color}${ALPHA};`;
|
|
658
|
+
const statusStyle = (color) => `font-weight: 700; padding: 2px 4px; border-radius: 4px; color: ${color}; background: ${color}${ALPHA};`;
|
|
659
|
+
const durationStyle = (duration) => duration >= 1000 ? 'color: #DD2A2A; font-weight: bold;' : 'color: #18BC36;';
|
|
799
660
|
const httpLogger = ({ request, duration, namespace, response }) => {
|
|
800
|
-
const
|
|
801
|
-
const
|
|
802
|
-
const
|
|
661
|
+
const origin = globalThis.location?.origin ?? FALLBACK_ORIGIN;
|
|
662
|
+
const url = new URL(request.urlWithParams, origin);
|
|
663
|
+
const method = request.method.toUpperCase();
|
|
664
|
+
const color = METHOD_COLORS[method] ?? UNKNOWN_COLOR;
|
|
665
|
+
const href = url.origin === origin ? url.pathname : url.href.replace(/^http/, 'http\u200B');
|
|
803
666
|
const queryParams = computeQueryParams(url);
|
|
804
|
-
const
|
|
805
|
-
console.groupCollapsed(`%c${namespace ?? ''}%c${method}%c${href}`,
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
console.log(
|
|
667
|
+
const status = response instanceof HttpResponseBase ? response.status : undefined;
|
|
668
|
+
console.groupCollapsed(`%c${namespace ?? ''}%c${method}%c${href}`, NAMESPACE_STYLE, methodStyle(color), hrefStyle(color));
|
|
669
|
+
try {
|
|
670
|
+
console.log(`%cStatus: %c${status ?? 'unknown'}`, TITLE_STYLE, statusStyle(STATUS_COLORS[computeStatusType(status)]));
|
|
671
|
+
if (url.searchParams.size > 0) {
|
|
672
|
+
logRow('Params', queryParams);
|
|
673
|
+
}
|
|
674
|
+
logRow('Headers', parseHttpHeaders(request.headers));
|
|
675
|
+
if (!isNil(request.body)) {
|
|
676
|
+
logRow('Body', computeRequestBody(request.body, request.headers.get('Content-Type') ?? ''));
|
|
677
|
+
}
|
|
678
|
+
logRow(response instanceof HttpResponse ? 'Response' : 'Error', response);
|
|
679
|
+
console.log(`%cDuration: %c${formatDuration(duration)}`, TITLE_STYLE, durationStyle(duration));
|
|
817
680
|
}
|
|
818
|
-
|
|
819
|
-
console.
|
|
681
|
+
finally {
|
|
682
|
+
console.groupEnd();
|
|
820
683
|
}
|
|
821
|
-
console.log(`%cDuration: %c${formatDuration(duration)}`, STYLES.title, STYLES.duration(duration));
|
|
822
|
-
console.groupEnd();
|
|
823
684
|
};
|
|
685
|
+
function logRow(label, value) {
|
|
686
|
+
console.log(`%c${label}:\n`, TITLE_STYLE, value);
|
|
687
|
+
}
|
|
824
688
|
function computeStatusType(status) {
|
|
825
689
|
if (!status)
|
|
826
690
|
return 'network';
|
|
@@ -867,122 +731,109 @@ function computeRequestBody(body, contentType) {
|
|
|
867
731
|
|
|
868
732
|
const DEFAULT_LOGGER_CONFIG = {
|
|
869
733
|
namespace: '[HTTP]',
|
|
870
|
-
|
|
734
|
+
filter: [],
|
|
871
735
|
};
|
|
872
736
|
|
|
873
737
|
const LOGGER_CONFIG = new InjectionToken('[LOGGER_CONFIG]: конфигурация логера', {
|
|
874
738
|
providedIn: 'root',
|
|
875
739
|
factory: () => DEFAULT_LOGGER_CONFIG,
|
|
876
740
|
});
|
|
877
|
-
const LOGGER_HANDLER = new InjectionToken('[LOGGER_HANDLER]:
|
|
741
|
+
const LOGGER_HANDLER = new InjectionToken('[LOGGER_HANDLER]: функция-обработчик для логирования (LoggerFn)', {
|
|
878
742
|
providedIn: 'root',
|
|
879
743
|
factory: () => httpLogger,
|
|
880
744
|
});
|
|
881
745
|
/**
|
|
882
746
|
* Контекстный токен для управления логированием конкретного HTTP-запроса.
|
|
883
|
-
* @description Имеет приоритет над глобальной конфигурацией (LoggerConfig.
|
|
747
|
+
* @description Имеет приоритет над глобальной конфигурацией (LoggerConfig.filter).
|
|
884
748
|
*
|
|
885
749
|
* Возможные значения:
|
|
886
|
-
* -
|
|
887
|
-
* -
|
|
888
|
-
* -
|
|
889
|
-
* - number
|
|
890
|
-
* - RegExp
|
|
750
|
+
* - null - значение не задано, применяется `filter` из конфигурации
|
|
751
|
+
* - false - отключить логирование для запроса
|
|
752
|
+
* - true - логировать все статусы
|
|
753
|
+
* - number - логировать только указанный статус
|
|
754
|
+
* - RegExp - логировать статусы, подходящие под регулярное выражение
|
|
755
|
+
* - Array - логировать статусы, совпавшие хотя бы с одним элементом
|
|
891
756
|
*
|
|
757
|
+
* @remarks Регулярное выражение проверяется по строке статуса, поэтому его
|
|
758
|
+
* стоит якорить: `/^5\d\d$/`, а не `/5\d/` - иначе совпадут и `250`, и `159`
|
|
892
759
|
* @example
|
|
893
|
-
*
|
|
894
|
-
* context:
|
|
760
|
+
* api.get('/users', null, {
|
|
761
|
+
* context: (ctx) => ctx.set(USE_LOGGER, 404),
|
|
895
762
|
* });
|
|
896
763
|
*/
|
|
897
|
-
const USE_LOGGER = new HttpContextToken(() =>
|
|
898
|
-
function provideLoggerConfig(config) {
|
|
899
|
-
return makeEnvironmentProviders([
|
|
900
|
-
{
|
|
901
|
-
provide: LOGGER_CONFIG,
|
|
902
|
-
useFactory: () => ({
|
|
903
|
-
...DEFAULT_LOGGER_CONFIG,
|
|
904
|
-
...resolveMaybeFn(config),
|
|
905
|
-
}),
|
|
906
|
-
},
|
|
907
|
-
]);
|
|
908
|
-
}
|
|
909
|
-
function provideLoggerHandler(handler) {
|
|
910
|
-
return makeEnvironmentProviders([
|
|
911
|
-
{
|
|
912
|
-
provide: LOGGER_HANDLER,
|
|
913
|
-
useValue: handler,
|
|
914
|
-
},
|
|
915
|
-
]);
|
|
916
|
-
}
|
|
764
|
+
const USE_LOGGER = new HttpContextToken(() => null);
|
|
917
765
|
|
|
918
|
-
function
|
|
766
|
+
function resolveFilterRules(request, config) {
|
|
919
767
|
const contextRule = request.context.get(USE_LOGGER);
|
|
920
|
-
if (contextRule
|
|
921
|
-
return
|
|
922
|
-
if (
|
|
923
|
-
return
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
return true;
|
|
929
|
-
return rule.url instanceof RegExp && rule.url.test(request.url);
|
|
930
|
-
});
|
|
931
|
-
if (foundRule) {
|
|
932
|
-
return foundRule.status ?? true;
|
|
933
|
-
}
|
|
934
|
-
return false;
|
|
935
|
-
}
|
|
936
|
-
function canLog(statusConfig, response) {
|
|
937
|
-
if (statusConfig === true)
|
|
938
|
-
return true;
|
|
939
|
-
if (isArray(statusConfig))
|
|
940
|
-
return statusConfig.includes(response.status);
|
|
941
|
-
if (statusConfig instanceof RegExp)
|
|
942
|
-
return statusConfig.test(response.status.toString());
|
|
943
|
-
return statusConfig === response.status;
|
|
768
|
+
if (contextRule === false)
|
|
769
|
+
return null;
|
|
770
|
+
if (contextRule === true)
|
|
771
|
+
return { method: request.method };
|
|
772
|
+
if (isDefined(contextRule))
|
|
773
|
+
return { status: contextRule };
|
|
774
|
+
const { filter } = config;
|
|
775
|
+
return isDefined(filter) && matchRequest(request, filter) ? filter : null;
|
|
944
776
|
}
|
|
945
777
|
const loggerInterceptor = (request, next) => {
|
|
946
778
|
const config = inject(LOGGER_CONFIG);
|
|
947
|
-
const
|
|
948
|
-
if (
|
|
779
|
+
const filter = resolveFilterRules(request, config);
|
|
780
|
+
if (isNil(filter))
|
|
949
781
|
return next(request);
|
|
950
|
-
}
|
|
951
782
|
const logger = inject(LOGGER_HANDLER);
|
|
952
783
|
if (!isFunction(logger)) {
|
|
953
784
|
console.warn('[HTTP]: Logger handler is not defined');
|
|
954
785
|
return next(request);
|
|
955
786
|
}
|
|
956
787
|
const started = performance.now();
|
|
957
|
-
|
|
958
|
-
if (
|
|
788
|
+
const log = (response) => {
|
|
789
|
+
if (!matchResponse(request, response, filter))
|
|
959
790
|
return;
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
791
|
+
logger({
|
|
792
|
+
namespace: config.namespace,
|
|
793
|
+
duration: performance.now() - started,
|
|
794
|
+
response,
|
|
795
|
+
request,
|
|
796
|
+
});
|
|
797
|
+
};
|
|
798
|
+
return next(request).pipe(tap((event) => {
|
|
799
|
+
if (event.type === HttpEventType.Response)
|
|
800
|
+
log(event);
|
|
968
801
|
}), catchError((error) => {
|
|
969
|
-
|
|
970
|
-
logger({
|
|
971
|
-
namespace: config.namespace,
|
|
972
|
-
response: error,
|
|
973
|
-
duration: performance.now() - started,
|
|
974
|
-
request,
|
|
975
|
-
});
|
|
976
|
-
}
|
|
802
|
+
log(error);
|
|
977
803
|
return throwError(() => error);
|
|
978
804
|
}));
|
|
979
805
|
};
|
|
980
806
|
|
|
807
|
+
/**
|
|
808
|
+
* Заменяет стандартный обработчик логов (`httpLogger`) на свой.
|
|
809
|
+
* @example
|
|
810
|
+
* provideLoggerConfig(
|
|
811
|
+
* { filter: { method: 'POST', url: '/api' } },
|
|
812
|
+
* withCustomLogger(({ request, response, duration }) => {
|
|
813
|
+
* Sentry.addBreadcrumb({ category: 'http', data: { url: request.url, duration } });
|
|
814
|
+
* }),
|
|
815
|
+
* );
|
|
816
|
+
*/
|
|
817
|
+
const withCustomHandler = defineKitFeature(0 /* FeatureKind.CustomHandler */, (handler) => ({
|
|
818
|
+
provide: LOGGER_HANDLER,
|
|
819
|
+
useValue: handler,
|
|
820
|
+
}));
|
|
821
|
+
function provideLoggerConfig(config, ...features) {
|
|
822
|
+
const providers = resolveConfigProviders(config, (data) => ({
|
|
823
|
+
provide: LOGGER_CONFIG,
|
|
824
|
+
useFactory: () => ({
|
|
825
|
+
...DEFAULT_LOGGER_CONFIG,
|
|
826
|
+
...resolveMaybeFn(data),
|
|
827
|
+
}),
|
|
828
|
+
}));
|
|
829
|
+
return makeEnvironmentProviders([...providers, ...collectFeatureProviders(config, ...features)]);
|
|
830
|
+
}
|
|
831
|
+
|
|
981
832
|
const MOCK_STORE = new Map();
|
|
982
|
-
const
|
|
833
|
+
const DEFAULT_MOCK_OPTIONS = {
|
|
983
834
|
enabled: false,
|
|
984
835
|
delay: 800,
|
|
985
|
-
errorChance: 0.
|
|
836
|
+
errorChance: 0.2,
|
|
986
837
|
fallbackErrors: new HttpErrorResponse({
|
|
987
838
|
status: 500,
|
|
988
839
|
error: 'Internal error',
|
|
@@ -990,7 +841,8 @@ const DEFAULT_CONFIG$1 = {
|
|
|
990
841
|
};
|
|
991
842
|
|
|
992
843
|
/**
|
|
993
|
-
* Регистрирует мок-конфигурацию
|
|
844
|
+
* Регистрирует мок-конфигурацию под идентификатором, который затем
|
|
845
|
+
* передаётся в запрос через `USE_MOCK`.
|
|
994
846
|
* @example
|
|
995
847
|
* defineMock('get-user', {
|
|
996
848
|
* response: { id: 1, name: 'Иван' },
|
|
@@ -1003,11 +855,15 @@ const DEFAULT_CONFIG$1 = {
|
|
|
1003
855
|
* }))
|
|
1004
856
|
* });
|
|
1005
857
|
*
|
|
858
|
+
* api.get('/users', null, {
|
|
859
|
+
* context: (ctx) => ctx.set(USE_MOCK, 'get-users-list'),
|
|
860
|
+
* });
|
|
861
|
+
*
|
|
1006
862
|
* @remarks
|
|
1007
863
|
* Если мок с таким `id` уже зарегистрирован, будет выведено предупреждение в консоль,
|
|
1008
864
|
* и существующая конфигурация не перезапишется.
|
|
1009
865
|
* @remarks
|
|
1010
|
-
*
|
|
866
|
+
* Функция сразу регистрирует конфигурацию в хранилище
|
|
1011
867
|
*/
|
|
1012
868
|
function defineMock(id, config) {
|
|
1013
869
|
if (MOCK_STORE.has(id)) {
|
|
@@ -1020,11 +876,27 @@ function defineMock(id, config) {
|
|
|
1020
876
|
});
|
|
1021
877
|
}
|
|
1022
878
|
|
|
879
|
+
/**
|
|
880
|
+
* Идентификатор мока, зарегистрированного через `defineMock`.
|
|
881
|
+
* @description Без него запрос уходит на сервер, даже если интерсептор включён.
|
|
882
|
+
* @example
|
|
883
|
+
* api.get('/users', null, {
|
|
884
|
+
* context: (ctx) => ctx.set(USE_MOCK, 'get-users-list'),
|
|
885
|
+
* });
|
|
886
|
+
* @default null
|
|
887
|
+
*/
|
|
1023
888
|
const USE_MOCK = new HttpContextToken(() => null);
|
|
1024
889
|
const MOCK_CONFIG = new InjectionToken('[MOCK_CONFIG]: Базовая конфигурация интерсептора', {
|
|
1025
890
|
providedIn: 'root',
|
|
1026
|
-
factory: () =>
|
|
891
|
+
factory: () => DEFAULT_MOCK_OPTIONS,
|
|
1027
892
|
});
|
|
893
|
+
/**
|
|
894
|
+
* Настраивает `mockInterceptor`.
|
|
895
|
+
* @description Сами моки регистрируются через `defineMock`, а привязываются
|
|
896
|
+
* к запросу контекстом `USE_MOCK`. По умолчанию интерсептор выключен.
|
|
897
|
+
* @example
|
|
898
|
+
* provideMockConfig({ enabled: !environment.production, delay: 300 });
|
|
899
|
+
*/
|
|
1028
900
|
function provideMockConfig(config) {
|
|
1029
901
|
return makeEnvironmentProviders([
|
|
1030
902
|
{
|
|
@@ -1032,7 +904,7 @@ function provideMockConfig(config) {
|
|
|
1032
904
|
useFactory: () => {
|
|
1033
905
|
const normalizedConfig = resolveMaybeFn(config);
|
|
1034
906
|
return {
|
|
1035
|
-
...
|
|
907
|
+
...DEFAULT_MOCK_OPTIONS,
|
|
1036
908
|
...normalizedConfig,
|
|
1037
909
|
};
|
|
1038
910
|
},
|
|
@@ -1088,88 +960,493 @@ const mockInterceptor = (request, next) => {
|
|
|
1088
960
|
return of(response).pipe(delay(config.delay));
|
|
1089
961
|
};
|
|
1090
962
|
|
|
963
|
+
var ErrorKind;
|
|
964
|
+
(function (ErrorKind) {
|
|
965
|
+
/**
|
|
966
|
+
* Сетевая ошибка.
|
|
967
|
+
* @description Например, недоступен сервер, обрыв соединения, DNS‑ошибка и т.п.
|
|
968
|
+
* Может не иметь валидного HTTP‑статуса.
|
|
969
|
+
*/
|
|
970
|
+
ErrorKind["Network"] = "Network";
|
|
971
|
+
/**
|
|
972
|
+
* Попытка обращения к несуществующим данным.
|
|
973
|
+
* @description Пример: отсутствует запись с указанным идентификатором.
|
|
974
|
+
* Обычно соответствует HTTP‑статусу `404 Not Found`.
|
|
975
|
+
*/
|
|
976
|
+
ErrorKind["NotExist"] = "NotExist";
|
|
977
|
+
/**
|
|
978
|
+
* Ошибка валидации входных данных.
|
|
979
|
+
* @description Переданные параметры не соответствуют требованиям API.
|
|
980
|
+
* Обычно соответствует HTTP‑статусу `400 Bad Request`.
|
|
981
|
+
*/
|
|
982
|
+
ErrorKind["Validation"] = "Validation";
|
|
983
|
+
/**
|
|
984
|
+
* Ошибка доступа (недостаточно прав).
|
|
985
|
+
* @description У пользователя нет прав на выполнение операции.
|
|
986
|
+
* Обычно соответствует HTTP‑статусу `403 Forbidden`.
|
|
987
|
+
*/
|
|
988
|
+
ErrorKind["Access"] = "Access";
|
|
989
|
+
/**
|
|
990
|
+
* Бизнес‑ошибка, возвращаемая доменным слоем/БД.
|
|
991
|
+
* @description Например, попытка создать дубликат сущности или нарушение бизнес‑правил.
|
|
992
|
+
* В типичном случае мапится на `418 I'm a teapot`
|
|
993
|
+
*/
|
|
994
|
+
ErrorKind["Domain"] = "Domain";
|
|
995
|
+
/**
|
|
996
|
+
* Таймаут запроса на стороне клиента.
|
|
997
|
+
* @description Превышено допустимое время ожидания ответа сервера.
|
|
998
|
+
* Обычно соответствует HTTP‑статусу `408 Request Timeout`.
|
|
999
|
+
*/
|
|
1000
|
+
ErrorKind["Timeout"] = "Timeout";
|
|
1001
|
+
/**
|
|
1002
|
+
* Пользователь не аутентифицирован.
|
|
1003
|
+
* @description Например, отсутствует или истёк токен доступа.
|
|
1004
|
+
* Обычно соответствует HTTP‑статусу `401 Unauthorized`.
|
|
1005
|
+
*/
|
|
1006
|
+
ErrorKind["Unauthorized"] = "Unauthorized";
|
|
1007
|
+
/**
|
|
1008
|
+
* Неизвестная ошибка.
|
|
1009
|
+
* @description Используется для любых ошибок, которые не подпадают
|
|
1010
|
+
* под остальные категории.
|
|
1011
|
+
*/
|
|
1012
|
+
ErrorKind["Unknown"] = "Unknown";
|
|
1013
|
+
})(ErrorKind || (ErrorKind = {}));
|
|
1014
|
+
|
|
1015
|
+
const PATH_SEPARATOR = /[\\/]+/;
|
|
1016
|
+
const ERROR_LOCATIONS = new Set(['body', 'header', 'path', 'query', 'env']);
|
|
1017
|
+
const DEFAULT_ERROR_MESSAGES = {
|
|
1018
|
+
[ErrorKind.Network]: 'Network error',
|
|
1019
|
+
[ErrorKind.NotExist]: 'Not found',
|
|
1020
|
+
[ErrorKind.Validation]: 'Validation error',
|
|
1021
|
+
[ErrorKind.Access]: 'Access denied',
|
|
1022
|
+
[ErrorKind.Domain]: 'Business rule violation',
|
|
1023
|
+
[ErrorKind.Timeout]: 'Request timeout',
|
|
1024
|
+
[ErrorKind.Unauthorized]: 'Unauthorized',
|
|
1025
|
+
[ErrorKind.Unknown]: 'Unknown error',
|
|
1026
|
+
};
|
|
1091
1027
|
const DEFAULT_OPEN_API_CONFIG = {
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1028
|
+
legacy: false,
|
|
1029
|
+
ignoredMessages: 'internal error',
|
|
1030
|
+
marker: {
|
|
1031
|
+
'X-Source': 'erp-open-api',
|
|
1096
1032
|
},
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1033
|
+
};
|
|
1034
|
+
|
|
1035
|
+
class ApiError extends Error {
|
|
1036
|
+
/** Тело ответа как пришло, без разбора */
|
|
1037
|
+
get payload() {
|
|
1038
|
+
return this.cause.error;
|
|
1039
|
+
}
|
|
1040
|
+
constructor(cause, options) {
|
|
1041
|
+
super(options.message ?? cause.message, { cause });
|
|
1042
|
+
this.name = 'ApiError';
|
|
1043
|
+
this.url = cause.url;
|
|
1044
|
+
this.kind = options.kind;
|
|
1045
|
+
this.status = cause.status;
|
|
1046
|
+
this.source = options.source;
|
|
1047
|
+
this.redirected = cause.redirected;
|
|
1048
|
+
this.details = options.details ?? [];
|
|
1049
|
+
}
|
|
1050
|
+
selectErrors(location = FORM_LOCATIONS) {
|
|
1051
|
+
const locations = toArray(location);
|
|
1052
|
+
return this.details.filter((item) => locations.includes(item.location));
|
|
1053
|
+
}
|
|
1054
|
+
/** Возвращает по умолчанию первое сообщение или список сообщений, если указан `separator` */
|
|
1055
|
+
selectMessages(location = FORM_LOCATIONS, separator = null) {
|
|
1056
|
+
const result = [];
|
|
1057
|
+
for (const item of this.selectErrors(location)) {
|
|
1058
|
+
if (!isNonEmptyString(item.message))
|
|
1059
|
+
continue;
|
|
1060
|
+
result.push(item.message);
|
|
1114
1061
|
}
|
|
1115
|
-
|
|
1116
|
-
|
|
1062
|
+
return isNil(separator) ? result.at(0) : result.join(separator);
|
|
1063
|
+
}
|
|
1064
|
+
/** Объект, где ключ - это путь до поля в точечной нотации, а значение - это сообщение об ошибке */
|
|
1065
|
+
selectErrorsByControl(location = FORM_LOCATIONS) {
|
|
1066
|
+
const result = {};
|
|
1067
|
+
for (const item of this.selectErrors(location)) {
|
|
1068
|
+
if (!isNonEmptyString(item.path) || !isNonEmptyString(item.message))
|
|
1069
|
+
continue;
|
|
1070
|
+
if (isDefined(result[item.path]))
|
|
1071
|
+
continue;
|
|
1072
|
+
result[item.path] = item.message;
|
|
1117
1073
|
}
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1074
|
+
return result;
|
|
1075
|
+
}
|
|
1076
|
+
toJSON() {
|
|
1077
|
+
return {
|
|
1078
|
+
name: this.name,
|
|
1079
|
+
message: this.message,
|
|
1080
|
+
kind: this.kind,
|
|
1081
|
+
source: this.source,
|
|
1082
|
+
status: this.status,
|
|
1083
|
+
url: this.url,
|
|
1084
|
+
details: this.details,
|
|
1085
|
+
};
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
const FORM_LOCATIONS = ['body', 'unknown'];
|
|
1089
|
+
function isApiError(data, kind) {
|
|
1090
|
+
if (data instanceof ApiError) {
|
|
1091
|
+
return isDefined(kind) ? data.kind === kind : true;
|
|
1092
|
+
}
|
|
1093
|
+
return false;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
function isSchemaError(data) {
|
|
1097
|
+
if (!isNumber(data['status']))
|
|
1098
|
+
return false;
|
|
1099
|
+
if (!isNonEmptyArray(data['errors']))
|
|
1100
|
+
return false;
|
|
1101
|
+
return data['errors'].every(isSchemaErrorItem);
|
|
1102
|
+
}
|
|
1103
|
+
function isSchemaErrorItem(data) {
|
|
1104
|
+
if (!isPlainObject(data))
|
|
1105
|
+
return false;
|
|
1106
|
+
if (!isNonEmptyString(data['message']))
|
|
1107
|
+
return false;
|
|
1108
|
+
if (isDefined(data['path']) && !isString(data['path']))
|
|
1109
|
+
return false;
|
|
1110
|
+
return isNil(data['location']) || isErrorLocation(data['location']);
|
|
1111
|
+
}
|
|
1112
|
+
function isDataBaseError(data) {
|
|
1113
|
+
if (!isNonEmptyString(data['message']))
|
|
1114
|
+
return false;
|
|
1115
|
+
if (isDefined(data['success']) && data['success'] !== false)
|
|
1116
|
+
return false;
|
|
1117
|
+
if (isDefined(data['status']) || isDefined(data['text']))
|
|
1118
|
+
return false;
|
|
1119
|
+
if (isDefined(data['error']) && !isPlainObject(data['error']))
|
|
1120
|
+
return false;
|
|
1121
|
+
if (isNonEmptyArray(data['errors']))
|
|
1122
|
+
return data['errors'].every(isDataBaseErrorItem);
|
|
1123
|
+
return isNil(data['errors']);
|
|
1124
|
+
}
|
|
1125
|
+
function isDataBaseErrorItem(data) {
|
|
1126
|
+
return isPlainObject(data) && isNonEmptyString(data['code']);
|
|
1127
|
+
}
|
|
1128
|
+
function isLegacyError(data) {
|
|
1129
|
+
if (isDefined(data['success']))
|
|
1130
|
+
return data['success'] === false || data['success'] === 0;
|
|
1131
|
+
if (isDefined(data['status']))
|
|
1132
|
+
return data['status'] === 'fail' || data['status'] === 'error';
|
|
1133
|
+
if (isNonEmptyString(data['error']) || isNumber(data['error']))
|
|
1134
|
+
return true;
|
|
1135
|
+
if (isNonEmptyArray(data['errors']))
|
|
1136
|
+
return true;
|
|
1137
|
+
return isPlainObject(data['errors']) && objectKeys(data['errors']).length > 0;
|
|
1138
|
+
}
|
|
1139
|
+
function fromSchemaDetails(data) {
|
|
1140
|
+
return data.errors.map((item) => ({
|
|
1141
|
+
message: item.message,
|
|
1142
|
+
...normalizePath(item.path, item.location),
|
|
1143
|
+
}));
|
|
1144
|
+
}
|
|
1145
|
+
function fromDataBaseDetails(data) {
|
|
1146
|
+
const items = data.errors ?? data.error?.errors ?? [];
|
|
1147
|
+
return items.reduce((details, item) => {
|
|
1148
|
+
if (!isNonEmptyString(item.message) && !isNonEmptyString(item.path))
|
|
1149
|
+
return details;
|
|
1150
|
+
details.push({
|
|
1151
|
+
message: item.message,
|
|
1152
|
+
...normalizePath(item.path),
|
|
1153
|
+
});
|
|
1154
|
+
return details;
|
|
1155
|
+
}, []);
|
|
1156
|
+
}
|
|
1157
|
+
function fromLegacyDetails(data) {
|
|
1158
|
+
if (!isArray(data.errors))
|
|
1159
|
+
return [];
|
|
1160
|
+
return data.errors.reduce((items, item) => {
|
|
1161
|
+
if (isNonEmptyString(item)) {
|
|
1162
|
+
items.push({
|
|
1163
|
+
message: item,
|
|
1164
|
+
location: 'unknown',
|
|
1165
|
+
});
|
|
1166
|
+
return items;
|
|
1131
1167
|
}
|
|
1132
|
-
|
|
1133
|
-
|
|
1168
|
+
if (!isPlainObject(item))
|
|
1169
|
+
return items;
|
|
1170
|
+
if (!isNonEmptyString(item['message']))
|
|
1171
|
+
return items;
|
|
1172
|
+
items.push({
|
|
1173
|
+
message: item['message'],
|
|
1174
|
+
...normalizePath(item['path'], item['location']),
|
|
1175
|
+
});
|
|
1176
|
+
return items;
|
|
1177
|
+
}, []);
|
|
1178
|
+
}
|
|
1179
|
+
function normalizePath(path, location) {
|
|
1180
|
+
const fallback = isErrorLocation(location) ? location : 'unknown';
|
|
1181
|
+
if (!isNonEmptyString(path))
|
|
1182
|
+
return { location: fallback };
|
|
1183
|
+
const segments = path.split(PATH_SEPARATOR).filter((item) => item.length > 0);
|
|
1184
|
+
const [head, ...rest] = segments;
|
|
1185
|
+
if (rest.length > 0 && isErrorLocation(head)) {
|
|
1186
|
+
return {
|
|
1187
|
+
path: rest.join('.'),
|
|
1188
|
+
location: head,
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
return {
|
|
1192
|
+
path: segments.length > 0 ? segments.join('.') : undefined,
|
|
1193
|
+
location: fallback,
|
|
1194
|
+
};
|
|
1195
|
+
}
|
|
1196
|
+
function pickMessage(predicate, ...messages) {
|
|
1197
|
+
for (const message of messages) {
|
|
1198
|
+
if (isNonEmptyString(message) && !predicate(message))
|
|
1199
|
+
return message;
|
|
1200
|
+
}
|
|
1201
|
+
return undefined;
|
|
1202
|
+
}
|
|
1203
|
+
function isErrorLocation(data) {
|
|
1204
|
+
return isString(data) && ERROR_LOCATIONS.has(data);
|
|
1205
|
+
}
|
|
1134
1206
|
|
|
1207
|
+
/** Включает или отключает разбор успешных ответов как легаси-ошибок для конкретного запроса */
|
|
1208
|
+
const USE_LEGACY_ERRORS = new HttpContextToken(() => null);
|
|
1209
|
+
/**
|
|
1210
|
+
* Сообщение для запроса, если бэк не прислал текст
|
|
1211
|
+
* @description Подставляется после текста из тела, но раньше сообщения по `kind`,
|
|
1212
|
+
* поэтому конкретика от бэка всегда важнее
|
|
1213
|
+
*/
|
|
1214
|
+
const USE_ERROR_MESSAGE = new HttpContextToken(() => null);
|
|
1215
|
+
/** Конфигурация для опен-апи интерсептора */
|
|
1135
1216
|
const OPEN_API_CONFIG = new InjectionToken('[OPEN_API_CONFIG]: конфигурация OpenApi-интерсептора', {
|
|
1136
1217
|
providedIn: 'root',
|
|
1137
1218
|
factory: () => DEFAULT_OPEN_API_CONFIG,
|
|
1138
1219
|
});
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1220
|
+
const IS_IGNORED_MESSAGE = new InjectionToken('[IS_IGNORED_MESSAGE]: проверка сообщения-заглушки', {
|
|
1221
|
+
providedIn: 'root',
|
|
1222
|
+
factory: () => {
|
|
1223
|
+
const { ignoredMessages } = inject(OPEN_API_CONFIG);
|
|
1224
|
+
if (isNil(ignoredMessages))
|
|
1225
|
+
return () => false;
|
|
1226
|
+
const normalize = (message) => message.trim().toLowerCase();
|
|
1227
|
+
const skipped = new Set(toArray(ignoredMessages).map(normalize));
|
|
1228
|
+
return (message) => skipped.has(normalize(message));
|
|
1229
|
+
},
|
|
1230
|
+
});
|
|
1231
|
+
const OPEN_API_RESPONSE_FILTER = new InjectionToken('[OPEN_API_RESPONSE_FILTER]: проверка принадлежности ответа API', {
|
|
1232
|
+
providedIn: 'root',
|
|
1233
|
+
factory: () => {
|
|
1234
|
+
const config = inject(OPEN_API_CONFIG);
|
|
1235
|
+
return (response, source) => {
|
|
1236
|
+
if (source !== 'unknown')
|
|
1237
|
+
return true;
|
|
1238
|
+
if ([0, 401, 408].includes(response.status))
|
|
1239
|
+
return true;
|
|
1240
|
+
if (isNil(config.marker))
|
|
1241
|
+
return false;
|
|
1242
|
+
return objectEntries(config.marker).every(([name, value]) => response.headers.get(name) === value);
|
|
1243
|
+
};
|
|
1244
|
+
},
|
|
1245
|
+
});
|
|
1246
|
+
const OPEN_API_KIND_RESOLVER = new InjectionToken('[OPEN_API_KIND_RESOLVER]: определение типа ошибки', {
|
|
1247
|
+
providedIn: 'root',
|
|
1248
|
+
factory: () => {
|
|
1249
|
+
return ({ status, error }) => {
|
|
1250
|
+
if (status === 0) {
|
|
1251
|
+
if (isInstance(error, DOMException) && error.name === 'TimeoutError')
|
|
1252
|
+
return ErrorKind.Timeout;
|
|
1253
|
+
const offline = typeof navigator !== 'undefined' && !navigator.onLine;
|
|
1254
|
+
return offline ? ErrorKind.Network : ErrorKind.Unknown;
|
|
1255
|
+
}
|
|
1256
|
+
switch (status) {
|
|
1257
|
+
case 400:
|
|
1258
|
+
case 422:
|
|
1259
|
+
return ErrorKind.Validation;
|
|
1260
|
+
case 401:
|
|
1261
|
+
return ErrorKind.Unauthorized;
|
|
1262
|
+
case 403:
|
|
1263
|
+
return ErrorKind.Access;
|
|
1264
|
+
case 404:
|
|
1265
|
+
return ErrorKind.NotExist;
|
|
1266
|
+
case 408:
|
|
1267
|
+
return ErrorKind.Timeout;
|
|
1268
|
+
case 409:
|
|
1269
|
+
case 418:
|
|
1270
|
+
return ErrorKind.Domain;
|
|
1271
|
+
default:
|
|
1272
|
+
return ErrorKind.Unknown;
|
|
1273
|
+
}
|
|
1274
|
+
};
|
|
1275
|
+
},
|
|
1276
|
+
});
|
|
1277
|
+
const OPEN_API_MESSAGES = new InjectionToken('[OPEN_API_MESSAGES]: сообщение по типу ошибки', {
|
|
1278
|
+
providedIn: 'root',
|
|
1279
|
+
factory: () => (kind) => DEFAULT_ERROR_MESSAGES[kind],
|
|
1280
|
+
});
|
|
1153
1281
|
|
|
1154
1282
|
const openApiInterceptor = (request, next) => {
|
|
1155
1283
|
const config = inject(OPEN_API_CONFIG);
|
|
1284
|
+
const ignorePredicate = inject(IS_IGNORED_MESSAGE);
|
|
1285
|
+
const responseFilter = inject(OPEN_API_RESPONSE_FILTER);
|
|
1286
|
+
const kindResolver = inject(OPEN_API_KIND_RESOLVER);
|
|
1287
|
+
const resolveMessage = inject(OPEN_API_MESSAGES);
|
|
1288
|
+
const requestMessage = request.context.get(USE_ERROR_MESSAGE);
|
|
1289
|
+
const legacy = request.context.get(USE_LEGACY_ERRORS) ?? config.legacy;
|
|
1156
1290
|
return next(request).pipe(map((response) => {
|
|
1157
|
-
if (response.type !== HttpEventType.Response)
|
|
1291
|
+
if (!legacy || response.type !== HttpEventType.Response)
|
|
1158
1292
|
return response;
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1293
|
+
if (!isPlainObject(response.body) || !isLegacyError(response.body))
|
|
1294
|
+
return response;
|
|
1295
|
+
throw new HttpErrorResponse({
|
|
1296
|
+
error: response.body,
|
|
1297
|
+
status: response.status,
|
|
1298
|
+
statusText: response.statusText,
|
|
1299
|
+
headers: response.headers,
|
|
1300
|
+
url: response.url ?? undefined,
|
|
1301
|
+
});
|
|
1164
1302
|
}), catchError((error) => {
|
|
1165
|
-
if (!isInstance(error, HttpErrorResponse)
|
|
1303
|
+
if (!isInstance(error, HttpErrorResponse))
|
|
1166
1304
|
return throwError(() => error);
|
|
1167
|
-
|
|
1168
|
-
|
|
1305
|
+
const parsed = parseBody(error.error, ignorePredicate);
|
|
1306
|
+
if (!responseFilter(error, parsed.source))
|
|
1307
|
+
return throwError(() => error);
|
|
1308
|
+
const kind = kindResolver(error, parsed.source);
|
|
1309
|
+
const message = parsed.message ?? requestMessage ?? resolveMessage(kind) ?? DEFAULT_ERROR_MESSAGES[kind];
|
|
1310
|
+
return throwError(() => new ApiError(error, {
|
|
1311
|
+
kind,
|
|
1312
|
+
message,
|
|
1313
|
+
source: parsed.source,
|
|
1314
|
+
details: parsed.details,
|
|
1315
|
+
}));
|
|
1169
1316
|
}));
|
|
1170
1317
|
};
|
|
1318
|
+
function parseBody(payload, isIgnored) {
|
|
1319
|
+
if (!isPlainObject(payload))
|
|
1320
|
+
return { source: 'unknown', details: [] };
|
|
1321
|
+
if (isSchemaError(payload)) {
|
|
1322
|
+
return {
|
|
1323
|
+
source: 'schema',
|
|
1324
|
+
details: fromSchemaDetails(payload),
|
|
1325
|
+
};
|
|
1326
|
+
}
|
|
1327
|
+
if (isDataBaseError(payload)) {
|
|
1328
|
+
const items = payload.errors ?? payload.error?.errors ?? [];
|
|
1329
|
+
return {
|
|
1330
|
+
source: 'database',
|
|
1331
|
+
details: fromDataBaseDetails(payload),
|
|
1332
|
+
message: pickMessage(isIgnored, ...items.map((item) => item.message), payload.message),
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1335
|
+
if (isLegacyError(payload)) {
|
|
1336
|
+
const details = fromLegacyDetails(payload);
|
|
1337
|
+
return {
|
|
1338
|
+
source: 'legacy',
|
|
1339
|
+
details,
|
|
1340
|
+
message: pickMessage(isIgnored, payload.message, payload.text, payload.error, details.at(0)?.message),
|
|
1341
|
+
};
|
|
1342
|
+
}
|
|
1343
|
+
return {
|
|
1344
|
+
source: 'unknown',
|
|
1345
|
+
details: [],
|
|
1346
|
+
message: pickMessage(isIgnored, payload['message'], payload['text'], payload['error']),
|
|
1347
|
+
};
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
function provideOpenApiConfig(config, ...features) {
|
|
1351
|
+
const providers = resolveConfigProviders(config, (item) => ({
|
|
1352
|
+
provide: OPEN_API_CONFIG,
|
|
1353
|
+
useFactory: () => mergeConfig(resolveMaybeFn(item)),
|
|
1354
|
+
}));
|
|
1355
|
+
return makeEnvironmentProviders([...providers, ...collectFeatureProviders(config, ...features)]);
|
|
1356
|
+
}
|
|
1357
|
+
/**
|
|
1358
|
+
* Переопределяет проверку обрабатывать ли ошибку в запросе.
|
|
1359
|
+
* @description Фабрика вызывается один раз в контексте инъекции - внутри доступен `inject()`
|
|
1360
|
+
*
|
|
1361
|
+
* По умолчанию ответ признаётся принадлежащим API, если тело удалось разобрать
|
|
1362
|
+
* (`source !== 'unknown'`), либо статус входит в `0`, `401`, `408`,
|
|
1363
|
+
* либо совпал `marker` из конфигурации.
|
|
1364
|
+
* @example
|
|
1365
|
+
* provideOpenApiConfig(
|
|
1366
|
+
* withApiResponseFilter(() => (response, source) => {
|
|
1367
|
+
* if (response.url?.includes('/external/')) return false;
|
|
1368
|
+
*
|
|
1369
|
+
* return source !== 'unknown';
|
|
1370
|
+
* }),
|
|
1371
|
+
* );
|
|
1372
|
+
*/
|
|
1373
|
+
const withApiResponseFilter = defineKitFeature(0 /* FeatureKind.ApiResponseFilter */, (factory) => ({
|
|
1374
|
+
provide: OPEN_API_RESPONSE_FILTER,
|
|
1375
|
+
useFactory: factory,
|
|
1376
|
+
}));
|
|
1377
|
+
/**
|
|
1378
|
+
* Определение типа ошибки по статусу и формату тела.
|
|
1379
|
+
* @description Фабрика вызывается один раз в контексте инъекции - внутри доступен `inject()`
|
|
1380
|
+
* По умолчанию:
|
|
1381
|
+
* - `0` - Timeout при `TimeoutError`, иначе Network (офлайн) или Unknown;
|
|
1382
|
+
* - `400` `422` - Validation;
|
|
1383
|
+
* - `401` - Unauthorized;
|
|
1384
|
+
* - `403` - Access;
|
|
1385
|
+
* - `404` - NotExist;
|
|
1386
|
+
* - `408` - Timeout;
|
|
1387
|
+
* - `409` `418` - Domain;
|
|
1388
|
+
* - остальное - Unknown.
|
|
1389
|
+
*
|
|
1390
|
+
* Второй аргумент `source` - формат, в котором удалось разобрать тело
|
|
1391
|
+
* (`schema`, `database`, `legacy`, `unknown`). Полезен, когда статус
|
|
1392
|
+
* ни о чём не говорит: например, легаси-ошибка приходит с `200`.
|
|
1393
|
+
* @example
|
|
1394
|
+
* provideOpenApiConfig(
|
|
1395
|
+
* { legacy: true },
|
|
1396
|
+
* withApiKindResolver(() => (response, source) => {
|
|
1397
|
+
* if (source === 'legacy') return ApiErrorKind.Domain;
|
|
1398
|
+
*
|
|
1399
|
+
* return response.status === 402 ? ApiErrorKind.Access : ApiErrorKind.Unknown;
|
|
1400
|
+
* }),
|
|
1401
|
+
* );
|
|
1402
|
+
*/
|
|
1403
|
+
const withKindResolver = defineKitFeature(1 /* FeatureKind.KindResolver */, (factory) => ({
|
|
1404
|
+
provide: OPEN_API_KIND_RESOLVER,
|
|
1405
|
+
useFactory: factory,
|
|
1406
|
+
}));
|
|
1407
|
+
/**
|
|
1408
|
+
* Задаёт сообщения по типу ошибки.
|
|
1409
|
+
* @description Объект - статичные тексты, фабрика - вычисление на каждую ошибку.
|
|
1410
|
+
* Незаданные типы и `undefined` из резолвера берутся из сообщений кита.
|
|
1411
|
+
*
|
|
1412
|
+
* Сообщение используется, только если бэк не прислал свой текст: приоритет
|
|
1413
|
+
* такой - тело ответа, затем `USE_ERROR_MESSAGE`, затем эти сообщения.
|
|
1414
|
+
* @example
|
|
1415
|
+
* provideOpenApiConfig(
|
|
1416
|
+
* withApiErrorMessages({
|
|
1417
|
+
* [ApiErrorKind.Network]: 'Нет связи с сервером',
|
|
1418
|
+
* [ApiErrorKind.Validation]: 'Проверьте заполнение формы',
|
|
1419
|
+
* }),
|
|
1420
|
+
* );
|
|
1421
|
+
* @example
|
|
1422
|
+
* provideOpenApiConfig(
|
|
1423
|
+
* withApiErrorMessages(() => {
|
|
1424
|
+
* const translate = inject(TranslateService);
|
|
1425
|
+
*
|
|
1426
|
+
* return (kind) => translate.instant(`errors.${kind}`);
|
|
1427
|
+
* }),
|
|
1428
|
+
* );
|
|
1429
|
+
*/
|
|
1430
|
+
const withErrorMessages = defineKitFeature(2 /* FeatureKind.Messages */, (messages) => isFunction(messages)
|
|
1431
|
+
? {
|
|
1432
|
+
provide: OPEN_API_MESSAGES,
|
|
1433
|
+
useFactory: messages,
|
|
1434
|
+
}
|
|
1435
|
+
: {
|
|
1436
|
+
provide: OPEN_API_MESSAGES,
|
|
1437
|
+
useValue: (kind) => messages[kind],
|
|
1438
|
+
});
|
|
1439
|
+
function mergeConfig(config) {
|
|
1440
|
+
return {
|
|
1441
|
+
legacy: config.legacy ?? DEFAULT_OPEN_API_CONFIG.legacy,
|
|
1442
|
+
ignoredMessages: isUndefined(config.ignoredMessages)
|
|
1443
|
+
? DEFAULT_OPEN_API_CONFIG.ignoredMessages
|
|
1444
|
+
: config.ignoredMessages,
|
|
1445
|
+
marker: isUndefined(config.marker) ? DEFAULT_OPEN_API_CONFIG.marker : config.marker,
|
|
1446
|
+
};
|
|
1447
|
+
}
|
|
1171
1448
|
|
|
1172
|
-
const
|
|
1449
|
+
const DEFAULT_RETRY_CONFIG = {
|
|
1173
1450
|
delay: 500,
|
|
1174
1451
|
maxRetries: 3,
|
|
1175
1452
|
delayMultiplier: 2,
|
|
@@ -1180,17 +1457,42 @@ const DEFAULT_CONFIG = {
|
|
|
1180
1457
|
rules: [],
|
|
1181
1458
|
};
|
|
1182
1459
|
|
|
1460
|
+
/**
|
|
1461
|
+
* Управление повторами для конкретного запроса.
|
|
1462
|
+
* @description Имеет приоритет над `rules` из конфигурации.
|
|
1463
|
+
*
|
|
1464
|
+
* Возможные значения:
|
|
1465
|
+
* - `true` - повторять по настройкам по умолчанию
|
|
1466
|
+
* - `false` - не повторять
|
|
1467
|
+
* - объект - частичное переопределение настроек по умолчанию
|
|
1468
|
+
* - `null` - применяются `rules`; если ни одно не совпало, повторов не будет
|
|
1469
|
+
* @example
|
|
1470
|
+
* api.post('/orders', body, {
|
|
1471
|
+
* context: (ctx) => ctx.set(USE_RETRY, { maxRetries: 1, status: [503] }),
|
|
1472
|
+
* });
|
|
1473
|
+
* @default null
|
|
1474
|
+
*/
|
|
1183
1475
|
const USE_RETRY = new HttpContextToken(() => null);
|
|
1184
1476
|
const RETRY_CONFIG = new InjectionToken('[RETRY_CONFIG]: конфигурация retry-интерсептора', {
|
|
1185
1477
|
providedIn: 'root',
|
|
1186
|
-
factory: () =>
|
|
1478
|
+
factory: () => DEFAULT_RETRY_CONFIG,
|
|
1187
1479
|
});
|
|
1480
|
+
/**
|
|
1481
|
+
* Настраивает `retryInterceptor`.
|
|
1482
|
+
* @description По умолчанию `rules` пуст - повторов нет, пока не совпало
|
|
1483
|
+
* правило или не задан `USE_RETRY`. Учитывается заголовок `Retry-After`.
|
|
1484
|
+
* @example
|
|
1485
|
+
* provideRetryConfig({
|
|
1486
|
+
* maxRetries: 2,
|
|
1487
|
+
* rules: [{ method: 'GET', url: /^\/api\// }],
|
|
1488
|
+
* });
|
|
1489
|
+
*/
|
|
1188
1490
|
function provideRetryConfig(config) {
|
|
1189
1491
|
return makeEnvironmentProviders([
|
|
1190
1492
|
{
|
|
1191
1493
|
provide: RETRY_CONFIG,
|
|
1192
1494
|
useFactory: () => ({
|
|
1193
|
-
...
|
|
1495
|
+
...DEFAULT_RETRY_CONFIG,
|
|
1194
1496
|
...resolveMaybeFn(config),
|
|
1195
1497
|
}),
|
|
1196
1498
|
},
|
|
@@ -1205,17 +1507,8 @@ function resolveConfig(request, { rules, ...defaultConfig }) {
|
|
|
1205
1507
|
if (isPlainObject(requestRetry)) {
|
|
1206
1508
|
return { ...defaultConfig, ...requestRetry };
|
|
1207
1509
|
}
|
|
1208
|
-
const
|
|
1209
|
-
|
|
1210
|
-
return;
|
|
1211
|
-
if (isString(rule.url))
|
|
1212
|
-
return request.url === rule.url;
|
|
1213
|
-
return rule.url.test(request.url);
|
|
1214
|
-
});
|
|
1215
|
-
if (matchedRule) {
|
|
1216
|
-
return { ...defaultConfig, ...matchedRule };
|
|
1217
|
-
}
|
|
1218
|
-
return null;
|
|
1510
|
+
const rule = toArray(rules).find((rule) => matchRequest(request, rule));
|
|
1511
|
+
return rule ? { ...defaultConfig, ...rule } : null;
|
|
1219
1512
|
}
|
|
1220
1513
|
function resolveRetryAfter(error) {
|
|
1221
1514
|
const retryAfter = error.headers.get('Retry-After');
|
|
@@ -1230,15 +1523,6 @@ function resolveRetryAfter(error) {
|
|
|
1230
1523
|
}
|
|
1231
1524
|
return null;
|
|
1232
1525
|
}
|
|
1233
|
-
function shouldRetryStatus(status, retryStatus) {
|
|
1234
|
-
if (isNumber(retryStatus))
|
|
1235
|
-
return status === retryStatus;
|
|
1236
|
-
if (isArray(retryStatus))
|
|
1237
|
-
return retryStatus.includes(status);
|
|
1238
|
-
if (retryStatus instanceof RegExp)
|
|
1239
|
-
return retryStatus.test(String(status));
|
|
1240
|
-
return false;
|
|
1241
|
-
}
|
|
1242
1526
|
function computeDelay(config, retryCount) {
|
|
1243
1527
|
const initialDelay = Math.max(0, config.delay);
|
|
1244
1528
|
const multiplier = config.delayMultiplier;
|
|
@@ -1273,7 +1557,7 @@ const retryInterceptor = (request, next) => {
|
|
|
1273
1557
|
count: config.maxRetries,
|
|
1274
1558
|
delay: (error, retryCount) => {
|
|
1275
1559
|
if (!isInstance(error, HttpErrorResponse) ||
|
|
1276
|
-
!
|
|
1560
|
+
!matchResponse(request, error, { status: config.status })) {
|
|
1277
1561
|
return throwError(() => error);
|
|
1278
1562
|
}
|
|
1279
1563
|
const delay = resolveRetryAfter(error) ?? computeDelay(config, retryCount - 1);
|
|
@@ -1289,14 +1573,38 @@ const retryInterceptor = (request, next) => {
|
|
|
1289
1573
|
const DEFAULT_TIMEOUT_CONFIG = {
|
|
1290
1574
|
timeout: 10000,
|
|
1291
1575
|
rules: [],
|
|
1292
|
-
message: 'Request Timeout',
|
|
1293
1576
|
};
|
|
1294
1577
|
|
|
1578
|
+
/**
|
|
1579
|
+
* Таймаут конкретного запроса в миллисекундах.
|
|
1580
|
+
* @description Имеет приоритет над `rules` и значением по умолчанию.
|
|
1581
|
+
*
|
|
1582
|
+
* Возможные значения:
|
|
1583
|
+
* - `number` - целое положительное значение, Angular бросит ошибку на `0` и дробных
|
|
1584
|
+
* - `false` - отключить таймаут для запроса
|
|
1585
|
+
* - `null` - применяются `rules`, затем `timeout` из конфигурации
|
|
1586
|
+
* @example
|
|
1587
|
+
* api.post('/upload', formData, {
|
|
1588
|
+
* context: (ctx) => ctx.set(USE_TIMEOUT, 120_000),
|
|
1589
|
+
* });
|
|
1590
|
+
* @default null
|
|
1591
|
+
*/
|
|
1295
1592
|
const USE_TIMEOUT = new HttpContextToken(() => null);
|
|
1296
1593
|
const TIMEOUT_CONFIG = new InjectionToken('[TIMEOUT_CONFIG]: глобальная конфигурация timeout интерсептора', {
|
|
1297
1594
|
providedIn: 'root',
|
|
1298
1595
|
factory: () => DEFAULT_TIMEOUT_CONFIG,
|
|
1299
1596
|
});
|
|
1597
|
+
/**
|
|
1598
|
+
* Настраивает `timeoutInterceptor`.
|
|
1599
|
+
* @description Проставляет запросам нативный таймаут Angular, поэтому действует
|
|
1600
|
+
* на весь трафик `HttpClient`, включая `httpResource`. `timeout: null` отключает
|
|
1601
|
+
* значение по умолчанию - работать будут только `rules`.
|
|
1602
|
+
* @example
|
|
1603
|
+
* provideTimeoutConfig({
|
|
1604
|
+
* timeout: 15_000,
|
|
1605
|
+
* rules: [{ method: 'POST', url: '/upload', timeout: 120_000 }],
|
|
1606
|
+
* });
|
|
1607
|
+
*/
|
|
1300
1608
|
function provideTimeoutConfig(config) {
|
|
1301
1609
|
return makeEnvironmentProviders([
|
|
1302
1610
|
{
|
|
@@ -1309,47 +1617,27 @@ function provideTimeoutConfig(config) {
|
|
|
1309
1617
|
]);
|
|
1310
1618
|
}
|
|
1311
1619
|
|
|
1312
|
-
function
|
|
1620
|
+
function resolveTimeout(request, { rules, timeout }) {
|
|
1313
1621
|
const requestTimeout = request.context.get(USE_TIMEOUT);
|
|
1314
|
-
if (
|
|
1315
|
-
return
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
return false;
|
|
1320
|
-
if (isString(rule.url))
|
|
1321
|
-
return request.url === rule.url;
|
|
1322
|
-
return rule.url.test(request.url);
|
|
1323
|
-
});
|
|
1324
|
-
if (matchedRule) {
|
|
1325
|
-
return { timeout: matchedRule.timeout ?? defaultConfig.timeout };
|
|
1326
|
-
}
|
|
1327
|
-
return defaultConfig;
|
|
1622
|
+
if (requestTimeout === false)
|
|
1623
|
+
return null;
|
|
1624
|
+
if (isNumber(requestTimeout))
|
|
1625
|
+
return requestTimeout;
|
|
1626
|
+
return toArray(rules).find((rule) => matchRequest(request, rule))?.timeout ?? timeout;
|
|
1328
1627
|
}
|
|
1329
1628
|
const timeoutInterceptor = (request, next) => {
|
|
1330
1629
|
if (isNumber(request.timeout)) {
|
|
1331
1630
|
return next(request);
|
|
1332
1631
|
}
|
|
1333
|
-
const
|
|
1334
|
-
|
|
1335
|
-
if (isNil(resolvedConfig))
|
|
1632
|
+
const timeout = resolveTimeout(request, inject(TIMEOUT_CONFIG));
|
|
1633
|
+
if (isNil(timeout))
|
|
1336
1634
|
return next(request);
|
|
1337
|
-
return next(request
|
|
1338
|
-
each: resolvedConfig.timeout,
|
|
1339
|
-
with: () => throwError(() => new HttpErrorResponse({
|
|
1340
|
-
status: 408,
|
|
1341
|
-
url: request.url,
|
|
1342
|
-
error: {
|
|
1343
|
-
success: false,
|
|
1344
|
-
message: config.message,
|
|
1345
|
-
},
|
|
1346
|
-
})),
|
|
1347
|
-
}));
|
|
1635
|
+
return next(request.clone({ timeout }));
|
|
1348
1636
|
};
|
|
1349
1637
|
|
|
1350
1638
|
/**
|
|
1351
1639
|
* Generated bundle index. Do not edit.
|
|
1352
1640
|
*/
|
|
1353
1641
|
|
|
1354
|
-
export {
|
|
1642
|
+
export { ApiError, ErrorKind as ApiErrorKind, HttpApiService, ProgressHttpService, USE_ERROR_MESSAGE, USE_HEADERS, USE_LEGACY_ERRORS, USE_LOGGER, USE_MOCK, USE_PROGRESS, USE_RETRY, USE_TIMEOUT, defineMock, headersInterceptor, httpLogger, isApiError, loggerInterceptor, mockInterceptor, openApiInterceptor, progressInterceptor, provideHeadersConfig, provideHttpApi, provideLoggerConfig, provideMockConfig, provideOpenApiConfig, provideProgressConfig, provideRetryConfig, provideTimeoutConfig, retryInterceptor, timeoutInterceptor, withErrorMessages as withApiErrorMessages, withKindResolver as withApiKindResolver, withApiResponseFilter, withBodyTransform, withCustomHandler as withCustomLogger, withHeaders, withHeadersResolver, withPrefix, withSerializeConfig };
|
|
1355
1643
|
//# sourceMappingURL=http.mjs.map
|