@dxtmisha/functional-basic 1.2.3 → 1.2.5

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,5 +1,5 @@
1
1
  import { ApiInstance } from './ApiInstance';
2
- import { ApiConfig, ApiFetch, ApiMethodItem, ApiPreparationEnd } from '../types/apiTypes';
2
+ import { ApiConfig, ApiDefaultValue, ApiFetch, ApiHeadersValue, ApiMethodItem, ApiPreparationEnd } from '../types/apiTypes';
3
3
  import { ApiStatus } from './ApiStatus';
4
4
  import { ApiResponse } from './ApiResponse';
5
5
  import { ApiHydration } from './ApiHydration';
@@ -93,7 +93,7 @@ export declare class Api {
93
93
  * @param headers default headers / заголовки по умолчанию
94
94
  * @returns void / ничего не возвращает
95
95
  */
96
- static setHeaders(headers: Record<string, string> | (() => Record<string, string>)): void;
96
+ static setHeaders(headers: ApiHeadersValue): void;
97
97
  /**
98
98
  * Modifies the default request data.
99
99
  *
@@ -101,7 +101,7 @@ export declare class Api {
101
101
  * @param request default request data / данные запроса по умолчанию
102
102
  * @returns void / ничего не возвращает
103
103
  */
104
- static setRequestDefault(request: Record<string, any>): void;
104
+ static setRequestDefault(request: ApiDefaultValue): void;
105
105
  /**
106
106
  * Changes the base path to the script.
107
107
  *
@@ -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
  *
@@ -20,7 +20,7 @@ export declare class ApiDefault {
20
20
  * Получает данные запроса по умолчанию.
21
21
  * @returns default request data or undefined / данные запроса по умолчанию или undefined
22
22
  */
23
- get(): ApiDefaultValue | undefined;
23
+ get(): Record<string, any> | undefined;
24
24
  /**
25
25
  * Adds default data to the request.
26
26
  *
@@ -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,4 +1,4 @@
1
- import { ApiFetch } from '../types/apiTypes';
1
+ import { ApiFetch, ApiHeadersValue } from '../types/apiTypes';
2
2
  /**
3
3
  * Class for managing HTTP request headers.
4
4
  *
@@ -6,7 +6,7 @@ import { ApiFetch } from '../types/apiTypes';
6
6
  */
7
7
  export declare class ApiHeaders {
8
8
  /** Default headers / Заголовки по умолчанию */
9
- protected headers: Record<string, string>;
9
+ protected headers: ApiHeadersValue;
10
10
  /**
11
11
  * Gets the headers for the request.
12
12
  *
@@ -33,5 +33,5 @@ export declare class ApiHeaders {
33
33
  * @param headers list of default headers/ список заголовков по умолчанию
34
34
  * @returns this instance for chaining / текущий экземпляр для цепочки вызовов
35
35
  */
36
- set(headers: Record<string, string> | (() => Record<string, string>)): this;
36
+ set(headers: ApiHeadersValue): this;
37
37
  }
@@ -1,12 +1,13 @@
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 { ApiFetch, ApiMethod, ApiPreparationEnd } from '../types/apiTypes';
9
+ import { ApiStatus } from './ApiStatus';
10
+ import { ApiDefaultValue, ApiFetch, ApiHeadersValue, ApiMethod, ApiPreparationEnd } from '../types/apiTypes';
10
11
  /** Options for the API instance / Опции для экземпляра API */
11
12
  export type ApiInstanceOptions = {
12
13
  /** Class for working with headers / Класс для работы с заголовками */
@@ -134,14 +135,14 @@ export declare class ApiInstance {
134
135
  * Изменяет данные заголовка по умолчанию.
135
136
  * @param headers default headers / заголовки по умолчанию
136
137
  */
137
- setHeaders(headers: Record<string, string> | (() => Record<string, string>)): this;
138
+ setHeaders(headers: ApiHeadersValue): this;
138
139
  /**
139
140
  * Modifies the default request data.
140
141
  *
141
142
  * Изменяет данные запроса по умолчанию.
142
143
  * @param request default request data / данные запроса по умолчанию
143
144
  */
144
- setRequestDefault(request: Record<string, any>): this;
145
+ setRequestDefault(request: ApiDefaultValue): this;
145
146
  /**
146
147
  * Changes the base path to the script.
147
148
  *
@@ -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-запросов.
@@ -53,9 +54,9 @@ export type ApiConfig = {
53
54
  /** Base origin for API requests (protocol and domain)/ Базовый источник для API-запросов (протокол и домен) */
54
55
  origin?: string;
55
56
  /** Default headers for API requests/ Заголовки по умолчанию для API-запросов */
56
- headers?: Record<string, string>;
57
+ headers?: ApiHeadersValue;
57
58
  /** Default request data for API requests/ Данные запроса по умолчанию для API-запросов */
58
- requestDefault?: Record<string, any>;
59
+ requestDefault?: ApiDefaultValue;
59
60
  /** Function to call before request/ Функция для вызова перед запросом */
60
61
  preparation?: (apiFetch: ApiFetch) => Promise<void>;
61
62
  /** Function to call after request/ Функция для вызова после запроса */
@@ -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,11 +98,17 @@ 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
  };
104
+ /**
105
+ * Type for API request headers / Тип для заголовков запроса API
106
+ */
107
+ export type ApiHeadersValue = Record<string, string> | (() => Record<string, string>);
94
108
  /**
95
109
  * Default API request data type/ Тип данных запроса API по умолчанию
96
110
  */
97
- export type ApiDefaultValue = Record<string, any>;
111
+ export type ApiDefaultValue = Record<string, any> | (() => Record<string, any>);
98
112
  /**
99
113
  * Options for making API requests/ Опции для выполнения API-запросов
100
114
  */
@@ -137,6 +151,7 @@ export type ApiFetch = {
137
151
  globalEnd?: boolean;
138
152
  /** Additional fetch() options/ Дополнительные опции fetch() */
139
153
  init?: RequestInit;
154
+ initError?: boolean;
140
155
  /** Timeout for the request in milliseconds/ Таймаут запроса в миллисекундах */
141
156
  timeout?: number;
142
157
  /** AbortController for canceling the request/ AbortController для отмены запроса */
@@ -166,6 +181,27 @@ export type ApiHydrationItem = {
166
181
  * List of API hydration items/ Список элементов гидратации API
167
182
  */
168
183
  export type ApiHydrationList = ApiHydrationItem[];
184
+ /**
185
+ * Item for API error storage/ Элемент для хранилища ошибок API
186
+ */
187
+ export type ApiErrorStorageItem = {
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[];
169
205
  /**
170
206
  * Supported HTTP methods type/ Тип HTTP-методов
171
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.3",
4
+ "version": "1.2.5",
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": [