@dxtmisha/wiki 0.59.1 → 0.65.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/dist/{defineProperty-CbNEU1Ei.js → defineProperty-j1GyHeIL.js} +4 -4
- package/dist/library.js +1 -1
- package/dist/media.js +67 -33
- package/dist/src/media/descriptions/wikiDescriptionsBleed.d.ts +7 -0
- package/dist/src/media/descriptions/wikiDescriptionsDivider.d.ts +7 -0
- package/dist/src/media/descriptions/wikiDescriptionsMenuCountry.d.ts +7 -0
- package/dist/src/media/descriptions/wikiDescriptionsSwitch.d.ts +7 -0
- package/dist/src/media/descriptions/wikiDescriptionsTextDescription.d.ts +7 -0
- package/dist/src/media/descriptions/wikiDescriptionsTextLabel.d.ts +7 -0
- package/dist/src/media/mdx/Bleed/wikiMdxBleed.d.ts +7 -0
- package/dist/src/media/mdx/Divider/wikiMdxDivider.d.ts +7 -0
- package/dist/src/media/mdx/MenuCountry/wikiMdxMenuCountry.d.ts +3 -0
- package/dist/src/media/mdx/Switch/wikiMdxSwitch.d.ts +7 -0
- package/dist/src/media/mdx/TextDescription/wikiMdxTextDescription.d.ts +7 -0
- package/dist/src/media/mdx/TextLabel/wikiMdxTextLabel.d.ts +7 -0
- package/dist/src/media/props/wikiMenuCountry.d.ts +7 -0
- package/dist/storybook.js +2559 -1789
- package/dist/{wikiDescriptions-Dbkpa2Je.js → wikiDescriptions-CRalqVE2.js} +219 -1
- package/package.json +1 -1
- package/src/media/functional/functional/api/api.en.mdx +27 -0
- package/src/media/functional/functional/api/api.ru.mdx +27 -0
- package/src/media/functional/functional/api/api.vi.mdx +27 -0
- package/src/media/functional/functional/composables/useApiAsyncRef/useApiAsyncRef.en.mdx +22 -1
- package/src/media/functional/functional/composables/useApiAsyncRef/useApiAsyncRef.ru.mdx +22 -1
- package/src/media/functional/functional/composables/useApiAsyncRef/useApiAsyncRef.vi.mdx +22 -1
- package/src/media/functional/functional/composables/useApiDelete/useApiDelete.en.mdx +19 -15
- package/src/media/functional/functional/composables/useApiDelete/useApiDelete.ru.mdx +19 -15
- package/src/media/functional/functional/composables/useApiDelete/useApiDelete.vi.mdx +22 -18
- package/src/media/functional/functional/composables/useApiGet/useApiGet.en.mdx +20 -15
- package/src/media/functional/functional/composables/useApiGet/useApiGet.ru.mdx +20 -15
- package/src/media/functional/functional/composables/useApiGet/useApiGet.vi.mdx +23 -18
- package/src/media/functional/functional/composables/{useApiManagementRef → useApiManagementAsyncRef}/useApiManagementAsyncRef.en.mdx +15 -2
- package/src/media/functional/functional/composables/{useApiManagementRef → useApiManagementAsyncRef}/useApiManagementAsyncRef.ru.mdx +15 -2
- package/src/media/functional/functional/composables/{useApiManagementRef → useApiManagementAsyncRef}/useApiManagementAsyncRef.vi.mdx +15 -2
- package/src/media/functional/functional/composables/useApiManagementRef/useApiManagementRef.en.mdx +10 -2
- package/src/media/functional/functional/composables/useApiManagementRef/useApiManagementRef.ru.mdx +12 -4
- package/src/media/functional/functional/composables/useApiManagementRef/useApiManagementRef.vi.mdx +10 -2
- package/src/media/functional/functional/composables/useApiPost/useApiPost.en.mdx +20 -15
- package/src/media/functional/functional/composables/useApiPost/useApiPost.ru.mdx +20 -15
- package/src/media/functional/functional/composables/useApiPost/useApiPost.vi.mdx +23 -18
- package/src/media/functional/functional/composables/useApiPut/useApiPut.en.mdx +23 -18
- package/src/media/functional/functional/composables/useApiPut/useApiPut.ru.mdx +23 -18
- package/src/media/functional/functional/composables/useApiPut/useApiPut.vi.mdx +26 -21
- package/src/media/functional/functional/composables/useApiRef/useApiRef.en.mdx +2 -0
- package/src/media/functional/functional/composables/useApiRef/useApiRef.ru.mdx +2 -0
- package/src/media/functional/functional/composables/useApiRef/useApiRef.vi.mdx +2 -0
- package/src/media/functional/functional/composables/useApiRequest/useApiRequest.en.mdx +23 -17
- package/src/media/functional/functional/composables/useApiRequest/useApiRequest.ru.mdx +23 -17
- package/src/media/functional/functional/composables/useApiRequest/useApiRequest.vi.mdx +26 -20
- package/src/media/functional/functional/dxt-functional-plugin/dxt-functional-plugin.en.mdx +16 -2
- package/src/media/functional/functional/dxt-functional-plugin/dxt-functional-plugin.ru.mdx +16 -2
- package/src/media/functional/functional/dxt-functional-plugin/dxt-functional-plugin.vi.mdx +16 -2
- package/src/media/functional/functional/functions/dxtFunctionalPlugin/dxtFunctionalPlugin.en.mdx +4 -1
- package/src/media/functional/functional/functions/dxtFunctionalPlugin/dxtFunctionalPlugin.ru.mdx +4 -1
- package/src/media/functional/functional/functions/dxtFunctionalPlugin/dxtFunctionalPlugin.vi.mdx +4 -1
- package/src/media/functional/functional-basic/api/api.en.mdx +55 -0
- package/src/media/functional/functional-basic/api/api.ru.mdx +55 -0
- package/src/media/functional/functional-basic/api/api.vi.mdx +55 -0
- package/src/media/functional/functional-basic/classes/ApiError/ApiError.en.mdx +44 -0
- package/src/media/functional/functional-basic/classes/ApiError/ApiError.ru.mdx +44 -0
- package/src/media/functional/functional-basic/classes/ApiError/ApiError.vi.mdx +44 -0
- package/src/media/functional/functional-basic/classes/ApiErrorItem/ApiErrorItem.en.mdx +31 -0
- package/src/media/functional/functional-basic/classes/ApiErrorItem/ApiErrorItem.ru.mdx +31 -0
- package/src/media/functional/functional-basic/classes/ApiErrorItem/ApiErrorItem.vi.mdx +31 -0
- package/src/media/functional/functional-basic/classes/ApiErrorStorage/ApiErrorStorage.en.mdx +51 -0
- package/src/media/functional/functional-basic/classes/ApiErrorStorage/ApiErrorStorage.ru.mdx +51 -0
- package/src/media/functional/functional-basic/classes/ApiErrorStorage/ApiErrorStorage.vi.mdx +51 -0
|
@@ -28,7 +28,20 @@ const functionalOptions: FunctionalPluginOptions = {
|
|
|
28
28
|
// Suffix to be appended to all page <title>
|
|
29
29
|
metaSuffix: ' | My App',
|
|
30
30
|
// Pass the router so services can access navigation
|
|
31
|
-
router
|
|
31
|
+
router,
|
|
32
|
+
// Error causes for error center
|
|
33
|
+
errorCauses: [
|
|
34
|
+
{ code: 'access_denied', message: 'Access denied' }
|
|
35
|
+
],
|
|
36
|
+
// Error handlers
|
|
37
|
+
errorHandlers: [
|
|
38
|
+
{
|
|
39
|
+
group: 'auth',
|
|
40
|
+
handlers: [
|
|
41
|
+
(cause) => console.error('Auth error:', cause.message)
|
|
42
|
+
]
|
|
43
|
+
}
|
|
44
|
+
]
|
|
32
45
|
}
|
|
33
46
|
|
|
34
47
|
// Use functional plugin
|
|
@@ -46,7 +59,8 @@ When you call `app.use(dxtFunctionalPlugin)`, the following steps occur automati
|
|
|
46
59
|
3. **`Icons` Initialization**: Configures the global SVG icon registry.
|
|
47
60
|
4. **`Meta` Initialization**: Automatically sets the browser tab suffix (via `useMeta().setSuffix()`) if provided.
|
|
48
61
|
5. **Vue Router Integration**: Globally registers the router object in the library's memory (`RouterItemRef`), allowing other functional services to use navigation even outside Vue components.
|
|
49
|
-
6. **`
|
|
62
|
+
6. **`ErrorCenter` Setup**: Configures predefined error causes (`ErrorCenter.addList`) and registers global error handlers (`ErrorCenter.addHandlerList`) in the central error registry.
|
|
63
|
+
7. **`executeUseGlobalInit()` Execution**: Automatically triggers the initialization of absolutely all global singletons created via `executeUseGlobal`. You no longer need to call it manually!
|
|
50
64
|
|
|
51
65
|
## Service Configuration
|
|
52
66
|
|
|
@@ -28,7 +28,20 @@ const functionalOptions: FunctionalPluginOptions = {
|
|
|
28
28
|
// Суффикс, который будет добавляться ко всем <title> страниц
|
|
29
29
|
metaSuffix: ' | Мое приложение',
|
|
30
30
|
// Передача роутера для работы навигации внутри сервисов
|
|
31
|
-
router
|
|
31
|
+
router,
|
|
32
|
+
// Причины ошибок для центра ошибок
|
|
33
|
+
errorCauses: [
|
|
34
|
+
{ code: 'access_denied', message: 'Доступ ограничен' }
|
|
35
|
+
],
|
|
36
|
+
// Обработчики ошибок
|
|
37
|
+
errorHandlers: [
|
|
38
|
+
{
|
|
39
|
+
group: 'auth',
|
|
40
|
+
handlers: [
|
|
41
|
+
(cause) => console.error('Ошибка авторизации:', cause.message)
|
|
42
|
+
]
|
|
43
|
+
}
|
|
44
|
+
]
|
|
32
45
|
}
|
|
33
46
|
|
|
34
47
|
// Подключаем функциональный плагин
|
|
@@ -46,7 +59,8 @@ app.mount('#app')
|
|
|
46
59
|
3. **Инициализация `Icons`**: Запускает конфигурацию глобального реестра иконок (SVG).
|
|
47
60
|
4. **Инициализация `Meta`**: Автоматически прописывает суффикс вкладки браузера (через `useMeta().setSuffix()`), если он был передан.
|
|
48
61
|
5. **Интеграция с Vue Router**: Глобально регистрирует объект роутера в памяти библиотеки (`RouterItemRef`), чтобы другие функциональные сервисы имели доступ к навигации даже за пределами компонентов.
|
|
49
|
-
6.
|
|
62
|
+
6. **Настройка `ErrorCenter`**: Настраивает предопределенный список причин ошибок (`ErrorCenter.addList`) и регистрирует обработчики (`ErrorCenter.addHandlerList`) в едином хранилище.
|
|
63
|
+
7. **Запуск `executeUseGlobalInit()`**: Автоматически триггерит инициализацию абсолютно всех глобальных синглтонов на базе `executeUseGlobal`. Заботиться о ручном вызове больше не нужно!
|
|
50
64
|
|
|
51
65
|
## Конфигурация сервисов
|
|
52
66
|
|
|
@@ -28,7 +28,20 @@ const functionalOptions: FunctionalPluginOptions = {
|
|
|
28
28
|
// Hậu tố được thêm vào sau bất cứ thẻ <title> nào của trang web
|
|
29
29
|
metaSuffix: ' | Ứng Dụng Của Tôi',
|
|
30
30
|
// Truyền đối tượng router để các dịch vụ nhận biết hệ thống điều hướng
|
|
31
|
-
router
|
|
31
|
+
router,
|
|
32
|
+
// Các nguyên nhân lỗi cho trung tâm lỗi
|
|
33
|
+
errorCauses: [
|
|
34
|
+
{ code: 'access_denied', message: 'Truy cập bị từ chối' }
|
|
35
|
+
],
|
|
36
|
+
// Các trình xử lý lỗi
|
|
37
|
+
errorHandlers: [
|
|
38
|
+
{
|
|
39
|
+
group: 'auth',
|
|
40
|
+
handlers: [
|
|
41
|
+
(cause) => console.error('Lỗi xác thực:', cause.message)
|
|
42
|
+
]
|
|
43
|
+
}
|
|
44
|
+
]
|
|
32
45
|
}
|
|
33
46
|
|
|
34
47
|
// Bật plugin chức năng
|
|
@@ -46,7 +59,8 @@ Lúc bạn kích hoạt `app.use(dxtFunctionalPlugin)`, các giải đoạn tu
|
|
|
46
59
|
3. **Khởi Chạy `Icons`**: Kết nối và điều hướng kho lưu trữ các tập SVG hình tượng biểu trưng toàn cục.
|
|
47
60
|
4. **Khởi Chạy `Meta`**: Khởi thiết lập hậu tố trực tiếp trên tab trình duyệt (sử dụng hàm `useMeta().setSuffix()`) nếu trường này được kê khai.
|
|
48
61
|
5. **Cộng Giao Động Vue Router**: Nạp đối tượng định tuyến này vào mạng lưới dữ liệu riêng của bộ thư viện (`RouterItemRef`), biến các chức năng điều khiển trở thành có thể dùng chung mở cho những dịch vụ khác dẫu là nằm tách khỏi phạm vi một component Vue.
|
|
49
|
-
6. **
|
|
62
|
+
6. **Thiết lập `ErrorCenter`**: Cấu hình danh sách các nguyên nhân lỗi định trước (`ErrorCenter.addList`) và đăng ký các hàm xử lý lỗi toàn cục (`ErrorCenter.addHandlerList`) vào kho lưu trữ lỗi tập trung.
|
|
63
|
+
7. **Bật `executeUseGlobalInit()` chạy thi hành**: Đánh thức một lần tự khởi điểm duy nhất hoàn toàn những global singletons đứng ở nền móng `executeUseGlobal`. Chấm dứt thao tác bạn cất công truy xuất thủ công.
|
|
50
64
|
|
|
51
65
|
## Tinh Chỉnh Dịch Vụ Mở Rộng
|
|
52
66
|
|
package/src/media/functional/functional/functions/dxtFunctionalPlugin/dxtFunctionalPlugin.en.mdx
CHANGED
|
@@ -43,7 +43,8 @@ When the plugin is installed, it performs the following steps in order:
|
|
|
43
43
|
3. **Icons**: Calls `Icons.setConfig()` with the provided `IconsConfig`.
|
|
44
44
|
4. **Meta**: Configures the default title suffix via `useMeta().setSuffix()`.
|
|
45
45
|
5. **Router**: Registers the router instance in `RouterItemRef`, making it accessible globally.
|
|
46
|
-
6. **
|
|
46
|
+
6. **ErrorCenter**: Configures the predefined list of error causes via `ErrorCenter.addList()` and registers error handlers via `ErrorCenter.addHandlerList()`.
|
|
47
|
+
7. **executeUseGlobalInit**: Triggers the batch initialization of all global singletons defined using `executeUseGlobal`.
|
|
47
48
|
|
|
48
49
|
## Data Types
|
|
49
50
|
|
|
@@ -56,6 +57,8 @@ The plugin uses the following interfaces for configuration:
|
|
|
56
57
|
- `icons?: IconsConfig` — Configuration for the global `Icons` registry.
|
|
57
58
|
- `metaSuffix?: string` — A string that will be appended to all page titles set via `useMeta()`.
|
|
58
59
|
- `router?: Router` — The Vue Router instance. If omitted, the plugin will attempt to extract it from `app.config.globalProperties.$router`.
|
|
60
|
+
- `errorCauses?: ErrorCenterCauseList` — Predefined list of error causes for `ErrorCenter`.
|
|
61
|
+
- `errorHandlers?: ErrorCenterHandlerList` — List of error handlers for `ErrorCenter`.
|
|
59
62
|
|
|
60
63
|
### `ApiConfig`
|
|
61
64
|
|
package/src/media/functional/functional/functions/dxtFunctionalPlugin/dxtFunctionalPlugin.ru.mdx
CHANGED
|
@@ -43,7 +43,8 @@ app.mount('#app')
|
|
|
43
43
|
3. **Icons**: Вызывает `Icons.setConfig()` с предоставленным `IconsConfig`.
|
|
44
44
|
4. **Meta**: Настраивает суффикс заголовка по умолчанию через `useMeta().setSuffix()`.
|
|
45
45
|
5. **Router**: Регистрирует экземпляр роутера в `RouterItemRef`, делая его доступным глобально.
|
|
46
|
-
6. **
|
|
46
|
+
6. **ErrorCenter**: Настраивает предопределенный список причин ошибок через `ErrorCenter.addList()` и регистрирует обработчики через `ErrorCenter.addHandlerList()`.
|
|
47
|
+
7. **executeUseGlobalInit**: Запускает пакетную инициализацию всех глобальных синглтонов, определенных с помощью `executeUseGlobal`.
|
|
47
48
|
|
|
48
49
|
## Типы данных
|
|
49
50
|
|
|
@@ -56,6 +57,8 @@ app.mount('#app')
|
|
|
56
57
|
- `icons?: IconsConfig` — Конфигурация для глобального реестра иконок `Icons`.
|
|
57
58
|
- `metaSuffix?: string` — Строка, которая будет добавлена ко всем заголовкам страниц, установленным через `useMeta()`.
|
|
58
59
|
- `router?: Router` — Экземпляр Vue Router. Если не указан, плагин попытается извлечь его из `app.config.globalProperties.$router`.
|
|
60
|
+
- `errorCauses?: ErrorCenterCauseList` — Список предопределенных причин ошибок для `ErrorCenter`.
|
|
61
|
+
- `errorHandlers?: ErrorCenterHandlerList` — Список обработчиков ошибок для `ErrorCenter`.
|
|
59
62
|
|
|
60
63
|
### `ApiConfig`
|
|
61
64
|
|
package/src/media/functional/functional/functions/dxtFunctionalPlugin/dxtFunctionalPlugin.vi.mdx
CHANGED
|
@@ -43,7 +43,8 @@ Khi plugin được cài đặt, nó thực hiện các bước sau theo thứ t
|
|
|
43
43
|
3. **Icons**: Gọi `Icons.setConfig()` với `IconsConfig` được cung cấp.
|
|
44
44
|
4. **Meta**: Cấu hình hậu tố cho tiêu đề thông qua `useMeta().setSuffix()`.
|
|
45
45
|
5. **Router**: Đăng ký router vào `RouterItemRef`, giúp có thể truy cập toàn cục.
|
|
46
|
-
6. **
|
|
46
|
+
6. **ErrorCenter**: Cấu hình danh sách nguyên nhân lỗi định trước thông qua `ErrorCenter.addList()` và đăng ký các trình xử lý lỗi thông qua `ErrorCenter.addHandlerList()`.
|
|
47
|
+
7. **executeUseGlobalInit**: Kích hoạt quá trình khởi tạo hàng loạt cho tất cả các đối tượng đơn lẻ được định nghĩa thông qua `executeUseGlobal`.
|
|
47
48
|
|
|
48
49
|
## Các kiểu dữ liệu
|
|
49
50
|
|
|
@@ -56,6 +57,8 @@ Plugin sử dụng các giao diện (interface) sau để cấu hình:
|
|
|
56
57
|
- `icons?: IconsConfig` — Cấu hình cho cơ sở dữ liệu biểu tượng `Icons` toàn cục.
|
|
57
58
|
- `metaSuffix?: string` — Chuỗi hậu tố sẽ được thêm vào tất cả tiêu đề trang được thiết lập thông qua `useMeta()`.
|
|
58
59
|
- `router?: Router` — Thực thể Vue Router. Nếu bỏ qua, plugin sẽ cố gắng lấy nó từ `app.config.globalProperties.$router`.
|
|
60
|
+
- `errorCauses?: ErrorCenterCauseList` — Danh sách các nguyên nhân lỗi định trước cho `ErrorCenter`.
|
|
61
|
+
- `errorHandlers?: ErrorCenterHandlerList` — Danh sách các trình xử lý lỗi cho `ErrorCenter`.
|
|
59
62
|
|
|
60
63
|
### `ApiConfig`
|
|
61
64
|
|
|
@@ -88,6 +88,45 @@ When forming the final URL, the class automatically replaces special markers wit
|
|
|
88
88
|
// If the current locale is 'en-US', the final path will be '/api/en-US/users'
|
|
89
89
|
const data = await Api.get({ path: '{locale}/users' })
|
|
90
90
|
```
|
|
91
|
+
|
|
92
|
+
## Status and Meta-information
|
|
93
|
+
|
|
94
|
+
The `Api` class automatically extracts metadata from the server response (e.g., `success`, `status`, `message`, `code`) and merges it with your data object. This allows you to receive both the payload and the execution result in a single object.
|
|
95
|
+
|
|
96
|
+
You can access the full status of the last request via the `getStatus()` method, which returns an instance of `ApiStatus`.
|
|
97
|
+
|
|
98
|
+
```javascript
|
|
99
|
+
const data = await Api.get({ path: 'users' })
|
|
100
|
+
const status = Api.getStatus()
|
|
101
|
+
|
|
102
|
+
console.log(status.getStatus()) // 200 (HTTP Status)
|
|
103
|
+
console.log(status.getStatusType()) // 'success' | 'error' | 'warning' | 'info'
|
|
104
|
+
console.log(status.getMessage()) // Server-provided message or status text
|
|
105
|
+
console.log(status.getResponse()) // Raw parsed response body
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Error Identification
|
|
109
|
+
|
|
110
|
+
The library provides a sophisticated error management system via `ApiError`. You can pre-register known API error patterns, and the system will automatically identify them based on status, codes, or custom validation functions.
|
|
111
|
+
|
|
112
|
+
```javascript
|
|
113
|
+
import { ApiError, ApiMethodItem } from '@dxtmisha/functional-basic'
|
|
114
|
+
|
|
115
|
+
// Registering a specific error pattern
|
|
116
|
+
ApiError.add({
|
|
117
|
+
url: 'users/login',
|
|
118
|
+
method: ApiMethodItem.post,
|
|
119
|
+
code: 'INVALID_CREDENTIALS',
|
|
120
|
+
message: 'Please check your username and password.'
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
// Processing the request
|
|
124
|
+
const status = Api.getStatus()
|
|
125
|
+
const errorItem = status.get()?.errorObject // ApiErrorItem instance
|
|
126
|
+
|
|
127
|
+
if (errorItem && errorItem.getCode() === 'INVALID_CREDENTIALS') {
|
|
128
|
+
// Handle specific error case
|
|
129
|
+
}
|
|
91
130
|
```
|
|
92
131
|
|
|
93
132
|
## Lifecycle Hooks
|
|
@@ -215,3 +254,19 @@ Api.getResponse().setDevMode(true)
|
|
|
215
254
|
```
|
|
216
255
|
|
|
217
256
|
The emulator triggers **before** the real `fetch` is executed. If no matching mock is found, `Api` will perform a regular network request.
|
|
257
|
+
|
|
258
|
+
## Advanced: ApiInstance
|
|
259
|
+
|
|
260
|
+
The `Api` class is a **static proxy** for a global instance of `ApiInstance`. This instance is stored in `ServerStorage`, ensuring isolation between requests during SSR and singleton behavior on the client.
|
|
261
|
+
|
|
262
|
+
For advanced scenarios—such as connecting to multiple independent APIs simultaneously or creating temporary isolated environments—you can instantiate `ApiInstance` directly.
|
|
263
|
+
|
|
264
|
+
```javascript
|
|
265
|
+
import { ApiInstance } from '@dxtmisha/functional-basic'
|
|
266
|
+
|
|
267
|
+
const secondaryApi = new ApiInstance()
|
|
268
|
+
secondaryApi.setUrl('https://another-api.com/')
|
|
269
|
+
secondaryApi.setHeaders({ 'X-Client-Id': '...' })
|
|
270
|
+
|
|
271
|
+
const data = await secondaryApi.get({ path: 'resource' })
|
|
272
|
+
```
|
|
@@ -88,6 +88,45 @@ Api.setConfig({
|
|
|
88
88
|
// Если текущая локаль 'ru-RU', итоговый путь будет '/api/ru-RU/users'
|
|
89
89
|
const data = await Api.get({ path: '{locale}/users' })
|
|
90
90
|
```
|
|
91
|
+
|
|
92
|
+
## Статус и мета-информация
|
|
93
|
+
|
|
94
|
+
Класс `Api` автоматически извлекает метаданные из ответа сервера (например, `success`, `status`, `message`, `code`) и объединяет их с вашим объектом данных. Это позволяет получать и полезную нагрузку, и результат выполнения в одном объекте.
|
|
95
|
+
|
|
96
|
+
Вы можете получить полный статус последнего запроса через метод `getStatus()`, который возвращает экземпляр `ApiStatus`.
|
|
97
|
+
|
|
98
|
+
```javascript
|
|
99
|
+
const data = await Api.get({ path: 'users' })
|
|
100
|
+
const status = Api.getStatus()
|
|
101
|
+
|
|
102
|
+
console.log(status.getStatus()) // 200 (HTTP статус)
|
|
103
|
+
console.log(status.getStatusType()) // 'success' | 'error' | 'warning' | 'info'
|
|
104
|
+
console.log(status.getMessage()) // Сообщение от сервера или текст статуса
|
|
105
|
+
console.log(status.getResponse()) // Исходное тело ответа после парсинга
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Идентификация ошибок
|
|
109
|
+
|
|
110
|
+
Библиотека предоставляет продвинутую систему управления ошибками через `ApiError`. Вы можете заранее зарегистрировать известные паттерны ошибок API, и система автоматически идентифицирует их на основе статуса, кодов или кастомных функций валидации.
|
|
111
|
+
|
|
112
|
+
```javascript
|
|
113
|
+
import { ApiError, ApiMethodItem } from '@dxtmisha/functional-basic'
|
|
114
|
+
|
|
115
|
+
// Регистрация конкретного паттерна ошибки
|
|
116
|
+
ApiError.add({
|
|
117
|
+
url: 'users/login',
|
|
118
|
+
method: ApiMethodItem.post,
|
|
119
|
+
code: 'INVALID_CREDENTIALS',
|
|
120
|
+
message: 'Пожалуйста, проверьте логин и пароль.'
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
// При выполнении запроса
|
|
124
|
+
const status = Api.getStatus()
|
|
125
|
+
const errorItem = status.get()?.errorObject // Экземпляр ApiErrorItem
|
|
126
|
+
|
|
127
|
+
if (errorItem && errorItem.getCode() === 'INVALID_CREDENTIALS') {
|
|
128
|
+
// Обработка конкретного случая ошибки
|
|
129
|
+
}
|
|
91
130
|
```
|
|
92
131
|
|
|
93
132
|
## Хуки жизненного цикла
|
|
@@ -215,3 +254,19 @@ Api.getResponse().setDevMode(true)
|
|
|
215
254
|
```
|
|
216
255
|
|
|
217
256
|
Эмулятор срабатывает **до** выполнения реального `fetch`. Если подходящий мок не найден, `Api` выполнит обычный сетевой запрос.
|
|
257
|
+
|
|
258
|
+
## Продвинутое использование: ApiInstance
|
|
259
|
+
|
|
260
|
+
Класс `Api` является **статическим прокси** для глобального экземпляра `ApiInstance`. Этот экземпляр хранится в `ServerStorage`, что обеспечивает изоляцию между запросами при SSR и поведение синглтона на клиенте.
|
|
261
|
+
|
|
262
|
+
Для продвинутых сценариев — например, при необходимости работы с несколькими независимыми API одновременно или создания временных изолированных окружений — вы можете создавать экземпляры `ApiInstance` напрямую.
|
|
263
|
+
|
|
264
|
+
```javascript
|
|
265
|
+
import { ApiInstance } from '@dxtmisha/functional-basic'
|
|
266
|
+
|
|
267
|
+
const secondaryApi = new ApiInstance()
|
|
268
|
+
secondaryApi.setUrl('https://another-api.com/')
|
|
269
|
+
secondaryApi.setHeaders({ 'X-Client-Id': '...' })
|
|
270
|
+
|
|
271
|
+
const data = await secondaryApi.get({ path: 'resource' })
|
|
272
|
+
```
|
|
@@ -88,6 +88,45 @@ Khi tạo URL cuối cùng, lớp sẽ tự động thay thế các nhãn đặc
|
|
|
88
88
|
// Nếu locale hiện tại là 'vi-VN', đường dẫn cuối cùng sẽ là '/api/vi-VN/users'
|
|
89
89
|
const data = await Api.get({ path: '{locale}/users' })
|
|
90
90
|
```
|
|
91
|
+
|
|
92
|
+
## Trạng thái và Thông tin meta
|
|
93
|
+
|
|
94
|
+
Lớp `Api` tự động trích xuất các siêu dữ liệu (metadata) từ phản hồi của máy chủ (ví dụ: `success`, `status`, `message`, `code`) và hợp nhất chúng với đối tượng dữ liệu của bạn. Điều này cho phép bạn nhận được cả nội dung dữ liệu và kết quả thực thi trong một đối tượng duy nhất.
|
|
95
|
+
|
|
96
|
+
Bạn có thể truy cập trạng thái đầy đủ của yêu cầu cuối cùng thông qua phương thức `getStatus()`, phương thức này trả về một instance của `ApiStatus`.
|
|
97
|
+
|
|
98
|
+
```javascript
|
|
99
|
+
const data = await Api.get({ path: 'users' })
|
|
100
|
+
const status = Api.getStatus()
|
|
101
|
+
|
|
102
|
+
console.log(status.getStatus()) // 200 (Trạng thái HTTP)
|
|
103
|
+
console.log(status.getStatusType()) // 'success' | 'error' | 'warning' | 'info'
|
|
104
|
+
console.log(status.getMessage()) // Thông báo từ máy chủ hoặc văn bản trạng thái
|
|
105
|
+
console.log(status.getResponse()) // Nội dung phản hồi thô đã được phân tích
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Nhận dạng lỗi
|
|
109
|
+
|
|
110
|
+
Thư viện cung cấp một hệ thống quản lý lỗi tinh vi thông qua `ApiError`. Bạn có thể đăng ký trước các mẫu lỗi API đã biết, và hệ thống sẽ tự động xác định chúng dựa trên trạng thái, mã lỗi hoặc các hàm xác thực tùy chỉnh.
|
|
111
|
+
|
|
112
|
+
```javascript
|
|
113
|
+
import { ApiError, ApiMethodItem } from '@dxtmisha/functional-basic'
|
|
114
|
+
|
|
115
|
+
// Đăng ký một mẫu lỗi cụ thể
|
|
116
|
+
ApiError.add({
|
|
117
|
+
url: 'users/login',
|
|
118
|
+
method: ApiMethodItem.post,
|
|
119
|
+
code: 'INVALID_CREDENTIALS',
|
|
120
|
+
message: 'Vui lòng kiểm tra lại tên đăng nhập và mật khẩu.'
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
// Xử lý yêu cầu
|
|
124
|
+
const status = Api.getStatus()
|
|
125
|
+
const errorItem = status.get()?.errorObject // Instance ApiErrorItem
|
|
126
|
+
|
|
127
|
+
if (errorItem && errorItem.getCode() === 'INVALID_CREDENTIALS') {
|
|
128
|
+
// Xử lý trường hợp lỗi cụ thể
|
|
129
|
+
}
|
|
91
130
|
```
|
|
92
131
|
|
|
93
132
|
## Hook vòng đời
|
|
@@ -215,3 +254,19 @@ Api.getResponse().setDevMode(true)
|
|
|
215
254
|
```
|
|
216
255
|
|
|
217
256
|
Trình giả lập sẽ kích hoạt **trước khi** lệnh `fetch` thực sự được thực hiện. Nếu không tìm thấy mock phù hợp, `Api` sẽ thực hiện một yêu cầu mạng thông thường.
|
|
257
|
+
|
|
258
|
+
## Nâng cao: ApiInstance
|
|
259
|
+
|
|
260
|
+
Lớp `Api` là một **static proxy** cho một instance toàn cục của `ApiInstance`. Instance này được lưu trữ trong `ServerStorage`, đảm bảo sự cô lập giữa các yêu cầu trong quá trình SSR và hành vi singleton trên máy khách.
|
|
261
|
+
|
|
262
|
+
Đối với các kịch bản nâng cao—chẳng hạn như kết nối với nhiều API độc lập khác nhau cùng một lúc hoặc tạo các môi trường cô lập tạm thời—bạn có thể khởi tạo `ApiInstance` trực tiếp.
|
|
263
|
+
|
|
264
|
+
```javascript
|
|
265
|
+
import { ApiInstance } from '@dxtmisha/functional-basic'
|
|
266
|
+
|
|
267
|
+
const secondaryApi = new ApiInstance()
|
|
268
|
+
secondaryApi.setUrl('https://another-api.com/')
|
|
269
|
+
secondaryApi.setHeaders({ 'X-Client-Id': '...' })
|
|
270
|
+
|
|
271
|
+
const data = await secondaryApi.get({ path: 'resource' })
|
|
272
|
+
```
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import {Meta} from '@storybook/addon-docs/blocks'
|
|
2
|
+
|
|
3
|
+
<Meta title='@dxtmisha/en/functional-basic/Classes/ApiError - Error Utility (Static)'/>
|
|
4
|
+
|
|
5
|
+
# ApiError Class
|
|
6
|
+
|
|
7
|
+
The `ApiError` class is a **Primary Utility (Static)** for managing API error storage and identifying failures. It provides a centralized, singleton-based interface for registering error patterns and transforming raw network responses into structured `ApiErrorItem` objects.
|
|
8
|
+
|
|
9
|
+
## Key Features
|
|
10
|
+
|
|
11
|
+
- **Static Interface** — manage error criteria and analyze responses without manual instantiation.
|
|
12
|
+
- **SSR-Safe Singleton** — utilizes `ServerStorage` to maintain isolated error storage across different requests during server-side rendering.
|
|
13
|
+
- **Pattern Registration** — simple API for adding individual error patterns or bulk lists for global error identification.
|
|
14
|
+
|
|
15
|
+
## Methods
|
|
16
|
+
|
|
17
|
+
### Storage Management
|
|
18
|
+
|
|
19
|
+
- `getStorage(): ApiErrorStorage` — Retrieves the internal singleton instance of the error storage.
|
|
20
|
+
- `add(item: ApiErrorStorageItem | ApiErrorStorageList): void` — Adds one or more error patterns to the global storage.
|
|
21
|
+
|
|
22
|
+
### Analysis
|
|
23
|
+
|
|
24
|
+
#### `getItem`
|
|
25
|
+
|
|
26
|
+
Analyzes a raw Fetch response and creates a structured `ApiErrorItem` instance. This is the primary method for processing API failures.
|
|
27
|
+
|
|
28
|
+
**Parameters:**
|
|
29
|
+
- `method: ApiMethodItem` — The HTTP method of the request.
|
|
30
|
+
- `response: Response` — The raw Fetch response object.
|
|
31
|
+
|
|
32
|
+
**Returns:** `Promise<ApiErrorItem>` — A structured error object containing analyzed details.
|
|
33
|
+
|
|
34
|
+
```javascript
|
|
35
|
+
try {
|
|
36
|
+
const response = await fetch('/api/user');
|
|
37
|
+
if (!response.ok) {
|
|
38
|
+
const errorItem = await ApiError.getItem(ApiMethodItem.get, response);
|
|
39
|
+
console.error(errorItem.getMessage());
|
|
40
|
+
}
|
|
41
|
+
} catch (e) {
|
|
42
|
+
// Handle network error
|
|
43
|
+
}
|
|
44
|
+
```
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import {Meta} from '@storybook/addon-docs/blocks'
|
|
2
|
+
|
|
3
|
+
<Meta title='@dxtmisha/ru/functional-basic/Classes/ApiError - Утилита ошибок (Статическая)'/>
|
|
4
|
+
|
|
5
|
+
# Класс ApiError
|
|
6
|
+
|
|
7
|
+
Класс `ApiError` является **основной утилитой (статической)** для управления хранилищем ошибок API и идентификации сбоев. Он предоставляет централизованный синглтон-интерфейс для регистрации паттернов ошибок и преобразования сырых сетевых ответов в структурированные объекты `ApiErrorItem`.
|
|
8
|
+
|
|
9
|
+
## Ключевые особенности
|
|
10
|
+
|
|
11
|
+
- **Статический интерфейс** — управление критериями ошибок и анализ ответов без необходимости создания экземпляра класса.
|
|
12
|
+
- **Безопасный синглтон для SSR** — использует `ServerStorage` для поддержания изолированного хранилища ошибок для разных запросов во время серверного рендеринга.
|
|
13
|
+
- **Регистрация паттернов** — простой API для добавления отдельных паттернов ошибок или массовых списков для глобальной идентификации ошибок.
|
|
14
|
+
|
|
15
|
+
## Методы
|
|
16
|
+
|
|
17
|
+
### Управление хранилищем
|
|
18
|
+
|
|
19
|
+
- `getStorage(): ApiErrorStorage` — Возвращает внутренний синглтон-экземпляр хранилища ошибок.
|
|
20
|
+
- `add(item: ApiErrorStorageItem | ApiErrorStorageList): void` — Добавляет один или несколько паттернов ошибок в глобальное хранилище.
|
|
21
|
+
|
|
22
|
+
### Анализ
|
|
23
|
+
|
|
24
|
+
#### `getItem`
|
|
25
|
+
|
|
26
|
+
Анализирует сырой ответ Fetch и создает структурированный экземпляр `ApiErrorItem`. Это основной метод для обработки сбоев API.
|
|
27
|
+
|
|
28
|
+
**Параметры:**
|
|
29
|
+
- `method: ApiMethodItem` — HTTP-метод запроса.
|
|
30
|
+
- `response: Response` — Сырой объект ответа Fetch.
|
|
31
|
+
|
|
32
|
+
**Возвращает:** `Promise<ApiErrorItem>` — Структурированный объект ошибки, содержащий проанализированные детали.
|
|
33
|
+
|
|
34
|
+
```javascript
|
|
35
|
+
try {
|
|
36
|
+
const response = await fetch('/api/user');
|
|
37
|
+
if (!response.ok) {
|
|
38
|
+
const errorItem = await ApiError.getItem(ApiMethodItem.get, response);
|
|
39
|
+
console.error(errorItem.getMessage());
|
|
40
|
+
}
|
|
41
|
+
} catch (e) {
|
|
42
|
+
// Обработка сетевой ошибки
|
|
43
|
+
}
|
|
44
|
+
```
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import {Meta} from '@storybook/addon-docs/blocks'
|
|
2
|
+
|
|
3
|
+
<Meta title='@dxtmisha/vi/functional-basic/Classes/ApiError - Tiện ích lỗi (Tĩnh)'/>
|
|
4
|
+
|
|
5
|
+
# Lớp ApiError
|
|
6
|
+
|
|
7
|
+
Lớp `ApiError` là một **Tiện ích chính (Tĩnh)** để quản lý bộ lưu trữ lỗi API và xác định các thất bại. Nó cung cấp một giao diện singleton tập trung để đăng ký các mẫu lỗi và chuyển đổi các phản hồi mạng thô thành các đối tượng `ApiErrorItem` có cấu trúc.
|
|
8
|
+
|
|
9
|
+
## Các tính năng chính
|
|
10
|
+
|
|
11
|
+
- **Giao diện tĩnh** — quản lý tiêu chí lỗi và phân tích phản hồi mà không cần khởi tạo thủ công.
|
|
12
|
+
- **Singleton an toàn cho SSR** — sử dụng `ServerStorage` để duy trì bộ lưu trữ lỗi riêng biệt giữa các yêu cầu khác nhau trong quá trình render phía máy chủ.
|
|
13
|
+
- **Đăng ký mẫu** — API đơn giản để thêm các mẫu lỗi riêng lẻ hoặc danh sách hàng loạt để nhận dạng lỗi toàn cầu.
|
|
14
|
+
|
|
15
|
+
## Các phương thức
|
|
16
|
+
|
|
17
|
+
### Quản lý bộ lưu trữ
|
|
18
|
+
|
|
19
|
+
- `getStorage(): ApiErrorStorage` — Lấy instance singleton nội bộ của bộ lưu trữ lỗi.
|
|
20
|
+
- `add(item: ApiErrorStorageItem | ApiErrorStorageList): void` — Thêm một hoặc nhiều mẫu lỗi vào bộ lưu trữ toàn cầu.
|
|
21
|
+
|
|
22
|
+
### Phân tích
|
|
23
|
+
|
|
24
|
+
#### `getItem`
|
|
25
|
+
|
|
26
|
+
Phân tích một phản hồi Fetch thô và tạo một instance `ApiErrorItem` có cấu trúc. Đây là phương thức chính để xử lý các thất bại API.
|
|
27
|
+
|
|
28
|
+
**Tham số:**
|
|
29
|
+
- `method: ApiMethodItem` — Phương thức HTTP của yêu cầu.
|
|
30
|
+
- `response: Response` — Đối tượng phản hồi Fetch thô.
|
|
31
|
+
|
|
32
|
+
**Trả về:** `Promise<ApiErrorItem>` — Một đối tượng lỗi có cấu trúc chứa các chi tiết đã được phân tích.
|
|
33
|
+
|
|
34
|
+
```javascript
|
|
35
|
+
try {
|
|
36
|
+
const response = await fetch('/api/user');
|
|
37
|
+
if (!response.ok) {
|
|
38
|
+
const errorItem = await ApiError.getItem(ApiMethodItem.get, response);
|
|
39
|
+
console.error(errorItem.getMessage());
|
|
40
|
+
}
|
|
41
|
+
} catch (e) {
|
|
42
|
+
// Xử lý lỗi mạng
|
|
43
|
+
}
|
|
44
|
+
```
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import {Meta} from '@storybook/addon-docs/blocks'
|
|
2
|
+
|
|
3
|
+
<Meta title='@dxtmisha/en/functional-basic/Classes/ApiErrorItem - Error Instance'/>
|
|
4
|
+
|
|
5
|
+
# ApiErrorItem Class
|
|
6
|
+
|
|
7
|
+
The `ApiErrorItem` class is a **data wrapper for API error responses**. It encapsulates the request context (method, response) and the identified error criteria from the storage, providing a unified interface for extracting error details.
|
|
8
|
+
|
|
9
|
+
## Key Features
|
|
10
|
+
|
|
11
|
+
- **Data Encapsulation** — stores the complete context of an API failure, including the raw Fetch `Response`.
|
|
12
|
+
- **Unified Extraction** — provides consistent access to error codes and messages regardless of whether they came from the response body or pre-defined storage criteria.
|
|
13
|
+
- **Dynamic Messaging** — resolves error messages using static strings or dynamic factory functions based on the response.
|
|
14
|
+
|
|
15
|
+
## Methods
|
|
16
|
+
|
|
17
|
+
### Accessors
|
|
18
|
+
|
|
19
|
+
- `getMethod(): ApiMethodItem` — Returns the HTTP method used for the request.
|
|
20
|
+
- `getResponse(): Response` — Returns the raw Fetch response object.
|
|
21
|
+
- `getError(): ApiErrorStorageItem` — Returns the identified error criteria from storage.
|
|
22
|
+
- `getStatus(): number` — Returns the HTTP status code.
|
|
23
|
+
|
|
24
|
+
### Data Extraction
|
|
25
|
+
|
|
26
|
+
- `getCode(): string | undefined` — Retrieves the error code from the storage criteria.
|
|
27
|
+
- `getMessage(): string | undefined` — Resolves the error message (checks storage criteria or falls back to response defaults).
|
|
28
|
+
|
|
29
|
+
## Architecture
|
|
30
|
+
|
|
31
|
+
`ApiErrorItem` is typically created by the `ApiError.getItem()` factory. It serves as the final product of the error analysis phase, ready to be consumed by UI components or logging services.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import {Meta} from '@storybook/addon-docs/blocks'
|
|
2
|
+
|
|
3
|
+
<Meta title='@dxtmisha/ru/functional-basic/Classes/ApiErrorItem - Экземпляр ошибки'/>
|
|
4
|
+
|
|
5
|
+
# Класс ApiErrorItem
|
|
6
|
+
|
|
7
|
+
Класс `ApiErrorItem` является **оберткой данных для ответов об ошибках API**. Он инкапсулирует контекст запроса (метод, ответ) и идентифицированные критерии ошибки из хранилища, предоставляя единый интерфейс для извлечения деталей ошибки.
|
|
8
|
+
|
|
9
|
+
## Ключевые особенности
|
|
10
|
+
|
|
11
|
+
- **Инкапсуляция данных** — хранит полный контекст сбоя API, включая сырой объект `Response` от Fetch.
|
|
12
|
+
- **Единое извлечение** — обеспечивает последовательный доступ к кодам и сообщениям об ошибках, независимо от того, были ли они получены из тела ответа или из предварительно определенных критериев хранилища.
|
|
13
|
+
- **Динамические сообщения** — разрешает сообщения об ошибках, используя статические строки или динамические функции-фабрики на основе ответа.
|
|
14
|
+
|
|
15
|
+
## Методы
|
|
16
|
+
|
|
17
|
+
### Аксессоры
|
|
18
|
+
|
|
19
|
+
- `getMethod(): ApiMethodItem` — Возвращает HTTP-метод, использованный для запроса.
|
|
20
|
+
- `getResponse(): Response` — Возвращает сырой объект ответа Fetch.
|
|
21
|
+
- `getError(): ApiErrorStorageItem` — Возвращает идентифицированные критерии ошибки из хранилища.
|
|
22
|
+
- `getStatus(): number` — Возвращает код статуса HTTP.
|
|
23
|
+
|
|
24
|
+
### Извлечение данных
|
|
25
|
+
|
|
26
|
+
- `getCode(): string | undefined` — Получает код ошибки из критериев хранилища.
|
|
27
|
+
- `getMessage(): string | undefined` — Разрешает сообщение об ошибке (проверяет критерии хранилища или использует значения по умолчанию из ответа).
|
|
28
|
+
|
|
29
|
+
## Архитектура
|
|
30
|
+
|
|
31
|
+
`ApiErrorItem` обычно создается фабрикой `ApiError.getItem()`. Он служит конечным продуктом фазы анализа ошибок, готовым к использованию компонентами UI или сервисами логирования.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import {Meta} from '@storybook/addon-docs/blocks'
|
|
2
|
+
|
|
3
|
+
<Meta title='@dxtmisha/vi/functional-basic/Classes/ApiErrorItem - Đối tượng lỗi'/>
|
|
4
|
+
|
|
5
|
+
# Lớp ApiErrorItem
|
|
6
|
+
|
|
7
|
+
Lớp `ApiErrorItem` là một **vỏ bọc dữ liệu cho các phản hồi lỗi API**. Nó đóng gói ngữ cảnh yêu cầu (phương thức, phản hồi) và các tiêu chí lỗi đã xác định từ bộ lưu trữ, cung cấp một giao diện thống nhất để trích xuất chi tiết lỗi.
|
|
8
|
+
|
|
9
|
+
## Các tính năng chính
|
|
10
|
+
|
|
11
|
+
- **Đóng gói dữ liệu** — lưu trữ ngữ cảnh đầy đủ của một lỗi API, bao gồm cả đối tượng `Response` thô từ Fetch.
|
|
12
|
+
- **Trích xuất thống nhất** — cung cấp khả năng truy cập nhất quán vào mã lỗi và thông báo bất kể chúng đến từ thân phản hồi hay các tiêu chí lưu trữ được xác định trước.
|
|
13
|
+
- **Thông báo động** — giải quyết các thông báo lỗi bằng cách sử dụng chuỗi tĩnh hoặc các hàm tạo thông báo động dựa trên phản hồi.
|
|
14
|
+
|
|
15
|
+
## Các phương thức
|
|
16
|
+
|
|
17
|
+
### Các phương thức truy cập (Accessors)
|
|
18
|
+
|
|
19
|
+
- `getMethod(): ApiMethodItem` — Trả về phương thức HTTP được sử dụng cho yêu cầu.
|
|
20
|
+
- `getResponse(): Response` — Trả về đối tượng phản hồi Fetch thô.
|
|
21
|
+
- `getError(): ApiErrorStorageItem` — Trả về tiêu chí lỗi đã xác định từ bộ lưu trữ.
|
|
22
|
+
- `getStatus(): number` — Trả về mã trạng thái HTTP.
|
|
23
|
+
|
|
24
|
+
### Trích xuất dữ liệu
|
|
25
|
+
|
|
26
|
+
- `getCode(): string | undefined` — Lấy mã lỗi từ tiêu chí lưu trữ.
|
|
27
|
+
- `getMessage(): string | undefined` — Giải quyết thông báo lỗi (kiểm tra tiêu chí lưu trữ hoặc quay lại mặc định của phản hồi).
|
|
28
|
+
|
|
29
|
+
## Kiến trúc
|
|
30
|
+
|
|
31
|
+
`ApiErrorItem` thường được tạo bởi factory `ApiError.getItem()`. Nó phục vụ như là sản phẩm cuối cùng của giai đoạn phân tích lỗi, sẵn sàng để được sử dụng bởi các thành phần UI hoặc dịch vụ ghi log.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import {Meta} from '@storybook/addon-docs/blocks'
|
|
2
|
+
|
|
3
|
+
<Meta title='@dxtmisha/en/functional-basic/Classes/ApiErrorStorage - Error Management'/>
|
|
4
|
+
|
|
5
|
+
# ApiErrorStorage Class
|
|
6
|
+
|
|
7
|
+
The `ApiErrorStorage` class is a **Manager for handling and identifying API error states**. It provides a centralized storage for API error criteria, allowing the system to identify specific errors by matching the response status, error code from the JSON body, request method, and URL.
|
|
8
|
+
|
|
9
|
+
## Key Features
|
|
10
|
+
|
|
11
|
+
- **Centralized Storage** — aggregate all known API error patterns in one place for consistent processing.
|
|
12
|
+
- **Pattern Matching** — identify errors by HTTP status, custom error codes, request methods, or URL patterns (including RegExp).
|
|
13
|
+
- **Structured Transformation** — transform raw network errors into structured application-level error items.
|
|
14
|
+
- **Custom Validation** — support for custom validation functions for complex error identification scenarios.
|
|
15
|
+
|
|
16
|
+
## Methods
|
|
17
|
+
|
|
18
|
+
### Management
|
|
19
|
+
|
|
20
|
+
- `add(item: ApiErrorStorageItem | ApiErrorStorageList): this` — Adds one or more error items or lists to the internal storage.
|
|
21
|
+
|
|
22
|
+
### Identification
|
|
23
|
+
|
|
24
|
+
#### `find`
|
|
25
|
+
|
|
26
|
+
Finds a matching error item in the storage by analyzing the response. It automatically attempts to extract the error code and message from the response body.
|
|
27
|
+
|
|
28
|
+
**Parameters:**
|
|
29
|
+
- `method: ApiMethodItem` — The HTTP method used for the request.
|
|
30
|
+
- `response: Response` — The Fetch API response object.
|
|
31
|
+
|
|
32
|
+
**Returns:** `Promise<ApiErrorStorageItem>` — The matched error item or a generated error item if no match is found.
|
|
33
|
+
|
|
34
|
+
```javascript
|
|
35
|
+
const errorItem = await errorStorage.find(ApiMethodItem.get, response);
|
|
36
|
+
|
|
37
|
+
if (errorItem.code === 'USER_NOT_FOUND') {
|
|
38
|
+
// Handle specific error
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Types
|
|
43
|
+
|
|
44
|
+
### ApiErrorStorageItem
|
|
45
|
+
|
|
46
|
+
- `url: string | RegExp` — URL string or regular expression to match the request URL.
|
|
47
|
+
- `method: ApiMethodItem` — HTTP method required for the match.
|
|
48
|
+
- `code?: string` — Optional error code to match against the JSON body.
|
|
49
|
+
- `status?: number` — Optional HTTP status code to match.
|
|
50
|
+
- `validation?: (response: Response) => boolean` — Optional custom validation function.
|
|
51
|
+
- `message?: string | ((response?: Response) => string)` — Optional error message or message factory.
|