@dxtmisha/functional-basic 1.2.4 → 1.2.6

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.
@@ -1,4 +1,5 @@
1
1
  import { ApiStatus } from './ApiStatus';
2
+ import { ApiErrorItem } from './ApiErrorItem';
2
3
  import { ApiData, ApiFetch, ApiPreparationEnd } from '../types/apiTypes';
3
4
  /**
4
5
  * Class for handling and processing data returned from an API request.
@@ -9,6 +10,7 @@ export declare class ApiDataReturn<T = any> {
9
10
  protected readonly apiFetch: ApiFetch;
10
11
  protected readonly query: Response;
11
12
  protected readonly end: ApiPreparationEnd;
13
+ protected readonly error?: ApiErrorItem | undefined;
12
14
  /**
13
15
  * Raw data received from the API/
14
16
  * Исходные данные, полученные от API
@@ -26,8 +28,9 @@ export declare class ApiDataReturn<T = any> {
26
28
  * @param apiFetch API fetch configuration / конфигурация запроса API
27
29
  * @param query response object / объект ответа
28
30
  * @param end preparation end data / данные завершения подготовки
31
+ * @param error error object / объект ошибки
29
32
  */
30
- constructor(apiFetch: ApiFetch, query: Response, end: ApiPreparationEnd);
33
+ constructor(apiFetch: ApiFetch, query: Response, end: ApiPreparationEnd, error?: ApiErrorItem | undefined);
31
34
  /**
32
35
  * Initializes the class by reading data from the response.
33
36
  *
@@ -0,0 +1,39 @@
1
+ import { ApiErrorItem } from './ApiErrorItem';
2
+ import { ApiErrorStorage } from './ApiErrorStorage';
3
+ import { ApiErrorStorageItem, ApiMethodItem } from '../types/apiTypes';
4
+ /**
5
+ * Utility class for managing the API error storage and creating error items.
6
+ * It provides a centralized way to access the error storage and wrap raw
7
+ * responses into structured error items.
8
+ *
9
+ * Утилитарный класс для управления хранилищем ошибок API и создания элементов ошибок.
10
+ * Обеспечивает централизованный способ доступа к хранилищу ошибок и оборачивания
11
+ * сырых ответов в структурированные элементы ошибок.
12
+ */
13
+ export declare class ApiError {
14
+ /**
15
+ * Retrieves the singleton instance of the API error storage.
16
+ *
17
+ * Возвращает синглтон-экземпляр хранилища ошибок API.
18
+ * @returns error storage instance / экземпляр хранилища ошибок
19
+ */
20
+ static getStorage(): ApiErrorStorage;
21
+ /**
22
+ * Adds an error item or a list of error items to the storage.
23
+ *
24
+ * Добавляет элемент ошибки или список элементов ошибок в хранилище.
25
+ * @param item error item or list of error items / элемент ошибки или список элементов ошибок
26
+ * @param url URL pattern or RegExp / шаблон URL или регулярное выражение
27
+ * @param method HTTP method of the request / HTTP-метод запроса
28
+ */
29
+ static add(item: Partial<ApiErrorStorageItem> | Partial<ApiErrorStorageItem>[], url?: string | RegExp, method?: ApiMethodItem): void;
30
+ /**
31
+ * Creates an ApiErrorItem by matching the response against stored error criteria.
32
+ *
33
+ * Создает ApiErrorItem путем сопоставления ответа с сохраненными критериями ошибок.
34
+ * @param method HTTP method of the request / HTTP-метод запроса
35
+ * @param response raw Fetch response / сырой ответ Fetch
36
+ * @returns structured error item / структурированный элемент ошибки
37
+ */
38
+ static getItem(method: ApiMethodItem, response: Response): Promise<ApiErrorItem>;
39
+ }
@@ -0,0 +1,70 @@
1
+ import { ApiErrorStorageItem, ApiMethodItem } from '../types/apiTypes';
2
+ /**
3
+ * Class for managing and extracting data from an API error response.
4
+ * It encapsulates the request method, raw response, and identified error criteria,
5
+ * providing unified methods to retrieve error codes, messages, and status.
6
+ *
7
+ * Класс для управления и извлечения данных из ответа об ошибке API.
8
+ * Инкапсулирует метод запроса, сырой ответ и идентифицированные критерии ошибки,
9
+ * предоставляя единые методы для получения кодов ошибок, сообщений и статуса.
10
+ */
11
+ export declare class ApiErrorItem {
12
+ protected readonly method: ApiMethodItem;
13
+ protected readonly response: Response;
14
+ protected readonly error: ApiErrorStorageItem;
15
+ /** Cached JSON response body / Кэшированное тело ответа JSON */
16
+ protected jsonResponse: any | undefined;
17
+ /**
18
+ * Constructor for ApiErrorItem.
19
+ *
20
+ * Конструктор для ApiErrorItem.
21
+ * @param method HTTP method used for the request / HTTP-метод, использованный для запроса
22
+ * @param response raw Fetch response object / сырой объект ответа Fetch
23
+ * @param error matched error item from storage (optional) / найденный элемент ошибки из хранилища (опционально)
24
+ */
25
+ constructor(method: ApiMethodItem, response: Response, error: ApiErrorStorageItem);
26
+ /**
27
+ * Returns the HTTP method used for the request.
28
+ *
29
+ * Возвращает HTTP-метод, использованный для запроса.
30
+ * @returns HTTP method / HTTP-метод
31
+ */
32
+ getMethod(): ApiMethodItem;
33
+ /**
34
+ * Returns the raw Fetch response object.
35
+ *
36
+ * Возвращает сырой объект ответа Fetch.
37
+ * @returns Fetch response / ответ Fetch
38
+ */
39
+ getResponse(): Response;
40
+ /**
41
+ * Returns the identified error item from storage if it exists.
42
+ *
43
+ * Возвращает идентифицированный элемент ошибки из хранилища, если он существует.
44
+ * @returns error item or undefined / элемент ошибки или undefined
45
+ */
46
+ getError(): ApiErrorStorageItem;
47
+ /**
48
+ * Asynchronously retrieves the error code from storage or the response body.
49
+ *
50
+ * Асинхронно получает код ошибки из хранилища или тела ответа.
51
+ * @returns error code or undefined / код ошибки или undefined
52
+ */
53
+ getCode(): string | undefined;
54
+ /**
55
+ * Asynchronously retrieves the error message.
56
+ * Checks the identified error item, the response body, or falls back to status text.
57
+ *
58
+ * Асинхронно получает сообщение об ошибке.
59
+ * Проверяет идентифицированный элемент ошибки, тело ответа или использует текст статуса.
60
+ * @returns error message or undefined / сообщение об ошибке или undefined
61
+ */
62
+ getMessage(): string | undefined;
63
+ /**
64
+ * Returns the HTTP status code of the response.
65
+ *
66
+ * Возвращает код статуса HTTP ответа.
67
+ * @returns status code / код статуса
68
+ */
69
+ getStatus(): number;
70
+ }
@@ -0,0 +1,84 @@
1
+ import { ApiErrorStorageList, ApiErrorStorageItem, ApiMethodItem } from '../types/apiTypes';
2
+ /**
3
+ * Manager for handling and identifying API error states.
4
+ *
5
+ * This class provides a centralized storage for API error criteria. It allows the system
6
+ * to identify specific errors by matching the response status, error code from the JSON body,
7
+ * request method, and URL. It is used to transform raw network errors into structured
8
+ * application-level error items for consistent processing.
9
+ *
10
+ * Менеджер для обработки и идентификации состояний ошибок API.
11
+ *
12
+ * Этот класс обеспечивает централизованное хранилище критериев ошибок API. Он позволяет
13
+ * системе идентифицировать конкретные ошибки путем сопоставления статуса ответа,
14
+ * кода ошибки из тела JSON, метода запроса и URL. Используется для преобразования
15
+ * сырых сетевых ошибок в структурированные элементы ошибок прикладного уровня для
16
+ * единообразной обработки.
17
+ */
18
+ export declare class ApiErrorStorage {
19
+ /** Error storage list / Список хранилища ошибок */
20
+ protected storage: ApiErrorStorageList;
21
+ /**
22
+ * Finds a matching error item in the storage by analyzing the response.
23
+ *
24
+ * Ищет подходящий элемент ошибки в хранилище путем анализа ответа.
25
+ * @param method API method / Метод API
26
+ * @param response fetch response / Ответ fetch
27
+ * @returns matched error item or undefined / найденный элемент ошибки или undefined
28
+ */
29
+ find(method: ApiMethodItem, response: Response): Promise<ApiErrorStorageItem>;
30
+ /**
31
+ * Adds one or more error items or lists to the internal storage.
32
+ *
33
+ * Добавляет один или несколько элементов или списков ошибок во внутреннее хранилище.
34
+ * @param item error item or list of items / элемент ошибки или список элементов
35
+ * @param url URL pattern or RegExp / шаблон URL или регулярное выражение
36
+ * @param method HTTP method of the request / HTTP-метод запроса
37
+ * @returns current instance / текущий экземпляр
38
+ */
39
+ add(item: Partial<ApiErrorStorageItem> | Partial<ApiErrorStorageItem>[], url?: string | RegExp, method?: ApiMethodItem): this;
40
+ /**
41
+ * Checks if the response matches the criteria of any stored error item.
42
+ *
43
+ * Проверяет, соответствует ли ответ критериям любого сохраненного элемента ошибки.
44
+ * @param method API method / Метод API
45
+ * @param response fetch response / Ответ fetch
46
+ * @param code error code from response body / код ошибки из тела ответа
47
+ * @returns matched error item or undefined if no match found / найденный элемент ошибки или undefined, если совпадений не найдено
48
+ */
49
+ protected findItem(method: ApiMethodItem, response: Response, code?: string): ApiErrorStorageItem | undefined;
50
+ /**
51
+ * Validates if the given URL matches the specified pattern.
52
+ *
53
+ * Проверяет, соответствует ли данный URL указанному шаблону.
54
+ * @param url URL to check / URL для проверки
55
+ * @param pattern URL pattern or RegExp / шаблон URL или регулярное выражение
56
+ * @returns true if the URL matches the pattern / true, если URL соответствует шаблону
57
+ */
58
+ protected isUrl(url: string, pattern: string | RegExp): boolean;
59
+ /**
60
+ * Attempts to extract an error code from the response body in JSON format.
61
+ *
62
+ * Пытается извлечь код ошибки из тела ответа в формате JSON.
63
+ * @param response fetch response / Ответ fetch
64
+ * @returns extracted error code or undefined / извлеченный код ошибки или undefined
65
+ */
66
+ protected getBody(response: Response): Promise<any>;
67
+ protected getDataByKey<R = string>(body: any, key: string): R | undefined;
68
+ /**
69
+ * Attempts to extract an error code from the response body in JSON format.
70
+ *
71
+ * Пытается извлечь код ошибки из тела ответа в формате JSON.
72
+ * @param response fetch response / Ответ fetch
73
+ * @returns extracted error code or undefined / извлеченный код ошибки или undefined
74
+ */
75
+ protected getCode(body: any): string | undefined;
76
+ /**
77
+ * Attempts to extract an error message from the response body in JSON format.
78
+ *
79
+ * Пытается извлечь сообщение об ошибке из тела ответа в формате JSON.
80
+ * @param body response body / тело ответа
81
+ * @returns extracted error message or undefined / извлеченное сообщение об ошибке или undefined
82
+ */
83
+ protected getMessage(body: any): string | undefined;
84
+ }
@@ -1,11 +1,12 @@
1
1
  import { LoadingInstance } from './LoadingInstance';
2
2
  import { ErrorCenterInstance } from './ErrorCenterInstance';
3
3
  import { ApiDefault } from './ApiDefault';
4
+ import { ApiErrorItem } from './ApiErrorItem';
4
5
  import { ApiHeaders } from './ApiHeaders';
5
6
  import { ApiHydration } from './ApiHydration';
6
7
  import { ApiPreparation } from './ApiPreparation';
7
- import { ApiStatus } from './ApiStatus';
8
8
  import { ApiResponse } from './ApiResponse';
9
+ import { ApiStatus } from './ApiStatus';
9
10
  import { ApiDefaultValue, ApiFetch, ApiHeadersValue, ApiMethod, ApiPreparationEnd } from '../types/apiTypes';
10
11
  /** Options for the API instance / Опции для экземпляра API */
11
12
  export type ApiInstanceOptions = {
@@ -268,9 +269,9 @@ export declare class ApiInstance {
268
269
  * Processes an error response.
269
270
  *
270
271
  * Обрабатывает ошибку ответа.
271
- * @param query error response / ответ с ошибкой
272
+ * @param error error details / данные ошибки
272
273
  */
273
- protected makeErrorQuery(query: Response): void;
274
+ protected makeErrorQuery(error: ApiErrorItem | Response): void;
274
275
  /**
275
276
  * Initialize controller for request with timeout support.
276
277
  *
@@ -2,6 +2,9 @@ export * from './classes/Api';
2
2
  export * from './classes/ApiCache';
3
3
  export * from './classes/ApiDataReturn';
4
4
  export * from './classes/ApiDefault';
5
+ export * from './classes/ApiError';
6
+ export * from './classes/ApiErrorItem';
7
+ export * from './classes/ApiErrorStorage';
5
8
  export * from './classes/ApiHeaders';
6
9
  export * from './classes/ApiHydration';
7
10
  export * from './classes/ApiInstance';
@@ -1,3 +1,4 @@
1
+ import { ApiErrorItem } from '../classes/ApiErrorItem';
1
2
  /**
2
3
  * Supported HTTP methods for API requests.
3
4
  * Поддерживаемые HTTP-методы для API-запросов.
@@ -79,6 +80,13 @@ export type ApiDataValidation = {
79
80
  code?: string | number;
80
81
  /** Message/ Сообщение */
81
82
  message?: string;
83
+ /** Error/ Ошибка */
84
+ error?: {
85
+ /** Code / Код */
86
+ code?: string | number;
87
+ /** Message/ Сообщение */
88
+ message?: string;
89
+ };
82
90
  };
83
91
  /**
84
92
  * Type of API response data item/ Тип элемента данных ответа API
@@ -90,6 +98,8 @@ export type ApiDataItem<T = any> = T & ApiDataValidation & {
90
98
  success?: boolean;
91
99
  /** Status object/ Объект статуса */
92
100
  statusObject?: ApiStatusItem;
101
+ /** Error object/ Объект ошибки */
102
+ errorObject?: ApiErrorItem;
93
103
  };
94
104
  /**
95
105
  * Type for API request headers / Тип для заголовков запроса API
@@ -141,6 +151,7 @@ export type ApiFetch = {
141
151
  globalEnd?: boolean;
142
152
  /** Additional fetch() options/ Дополнительные опции fetch() */
143
153
  init?: RequestInit;
154
+ initError?: boolean;
144
155
  /** Timeout for the request in milliseconds/ Таймаут запроса в миллисекундах */
145
156
  timeout?: number;
146
157
  /** AbortController for canceling the request/ AbortController для отмены запроса */
@@ -170,6 +181,27 @@ export type ApiHydrationItem = {
170
181
  * List of API hydration items/ Список элементов гидратации API
171
182
  */
172
183
  export type ApiHydrationList = ApiHydrationItem[];
184
+ /**
185
+ * Item for API error storage/ Элемент для хранилища ошибок API
186
+ */
187
+ export type ApiErrorStorageItem = Record<string, any> & {
188
+ /** URL string or RegExp to match request URL/ Строка URL или RegExp для сопоставления URL */
189
+ url: string | RegExp;
190
+ /** HTTP method/ HTTP метод */
191
+ method: ApiMethodItem;
192
+ /** Error code/ Код ошибки */
193
+ code?: string;
194
+ /** HTTP status code/ Код статуса HTTP */
195
+ status?: number;
196
+ /** Validation function/ Функция валидации */
197
+ validation?: (response: Response) => boolean;
198
+ /** Error message or function that returns message/ Сообщение об ошибке или функция, возвращающая сообщение */
199
+ message?: string | ((response?: Response) => string);
200
+ };
201
+ /**
202
+ * List of API error storage items/ Список элементов хранилища ошибок API
203
+ */
204
+ export type ApiErrorStorageList = ApiErrorStorageItem[];
173
205
  /**
174
206
  * Supported HTTP methods type/ Тип HTTP-методов
175
207
  * (derived from ApiMethodItem enum)/ (получен из перечисления ApiMethodItem)
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@dxtmisha/functional-basic",
3
3
  "private": false,
4
- "version": "1.2.4",
4
+ "version": "1.2.6",
5
5
  "type": "module",
6
6
  "description": "Foundational utility library for modern web development — HTTP client, geolocation, i18n, SEO meta tags, caching, storage, DOM utilities, and more. Framework-agnostic, zero dependencies, TypeScript-first.",
7
7
  "keywords": [