@igorchugurov/public-api-sdk 1.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/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Axon Dashboard
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md ADDED
@@ -0,0 +1,234 @@
1
+ # @igorchugurov/public-api-sdk
2
+
3
+ Переиспользуемый SDK для работы с универсальными сущностями (Entity Instances) в Axon Dashboard и других клиентских приложениях.
4
+
5
+ ## 📦 Установка
6
+
7
+ ```bash
8
+ # В монорепо (локально)
9
+ pnpm add @igorchugurov/public-api-sdk@workspace:*
10
+
11
+ # Или после публикации в npm
12
+ pnpm add @igorchugurov/public-api-sdk
13
+ ```
14
+
15
+ ## 🚀 Быстрый старт
16
+
17
+ ### 1. Server Component (SSR)
18
+
19
+ ```typescript
20
+ import { createServerSDK } from '@igorchugurov/public-api-sdk/server';
21
+ import { cookies } from 'next/headers';
22
+
23
+ export default async function MyPage({ params }) {
24
+ const { projectId } = await params;
25
+ const cookieStore = await cookies();
26
+
27
+ const sdk = await createServerSDK(
28
+ projectId,
29
+ {
30
+ supabaseUrl: process.env.NEXT_PUBLIC_SUPABASE_URL!,
31
+ supabaseAnonKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
32
+ cookies: {
33
+ getAll: () => cookieStore.getAll(),
34
+ setAll: (cookiesToSet) => {
35
+ cookiesToSet.forEach(({ name, value, options }) =>
36
+ cookieStore.set(name, value, options)
37
+ );
38
+ },
39
+ },
40
+ },
41
+ {
42
+ enableCache: true, // Кэшировать конфигурацию
43
+ }
44
+ );
45
+
46
+ // Получаем список экземпляров
47
+ const { data, pagination } = await sdk.getInstances(entityDefinitionId, {
48
+ page: 1,
49
+ limit: 20,
50
+ search: 'test',
51
+ });
52
+
53
+ return <div>{/* ... */}</div>;
54
+ }
55
+ ```
56
+
57
+ ### 2. Client Component
58
+
59
+ ```typescript
60
+ 'use client';
61
+
62
+ import { createClientSDK } from '@igorchugurov/public-api-sdk';
63
+
64
+ const sdk = createClientSDK(
65
+ projectId,
66
+ {
67
+ supabaseUrl: process.env.NEXT_PUBLIC_SUPABASE_URL!,
68
+ supabaseAnonKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
69
+ },
70
+ {
71
+ enableCache: true,
72
+ }
73
+ );
74
+
75
+ // Используем SDK
76
+ const { data, pagination } = await sdk.getInstances(entityDefinitionId, {
77
+ page: 1,
78
+ limit: 20,
79
+ });
80
+ ```
81
+
82
+ ## 📚 API Reference
83
+
84
+ ### CRUD операции
85
+
86
+ #### `getInstances(entityDefinitionId, params?)`
87
+
88
+ Получить список экземпляров с фильтрацией, поиском и пагинацией.
89
+
90
+ ```typescript
91
+ const { data, pagination } = await sdk.getInstances(entityDefinitionId, {
92
+ page?: number; // default: 1
93
+ limit?: number; // default: 20
94
+ search?: string;
95
+ filters?: Record<string, string[]>;
96
+ relationFilterModes?: Record<string, 'any' | 'all'>;
97
+ sortBy?: string; // default: 'created_at'
98
+ sortOrder?: 'asc' | 'desc'; // default: 'desc'
99
+ relationsAsIds?: boolean; // default: false
100
+ });
101
+ ```
102
+
103
+ #### `getInstance(entityDefinitionId, id, params?)`
104
+
105
+ Получить один экземпляр.
106
+
107
+ ```typescript
108
+ const instance = await sdk.getInstance(entityDefinitionId, id, {
109
+ relationsAsIds?: boolean; // default: false
110
+ });
111
+ ```
112
+
113
+ #### `createInstance(entityDefinitionId, data)`
114
+
115
+ Создать новый экземпляр.
116
+
117
+ ```typescript
118
+ const instance = await sdk.createInstance(entityDefinitionId, {
119
+ data: Record<string, unknown>;
120
+ relations?: Record<string, string[]>;
121
+ });
122
+ ```
123
+
124
+ #### `updateInstance(entityDefinitionId, id, data)`
125
+
126
+ Обновить экземпляр.
127
+
128
+ ```typescript
129
+ const instance = await sdk.updateInstance(entityDefinitionId, id, {
130
+ data: Record<string, unknown>;
131
+ relations?: Record<string, string[]>;
132
+ });
133
+ ```
134
+
135
+ #### `deleteInstance(entityDefinitionId, id)`
136
+
137
+ Удалить экземпляр.
138
+
139
+ ```typescript
140
+ await sdk.deleteInstance(entityDefinitionId, id);
141
+ ```
142
+
143
+ ### Конфигурация
144
+
145
+ #### `getEntityDefinitionConfig(entityDefinitionId)`
146
+
147
+ Получить конфигурацию EntityDefinition с полями.
148
+
149
+ ```typescript
150
+ const config = await sdk.getEntityDefinitionConfig(entityDefinitionId);
151
+ ```
152
+
153
+ #### `getEntityDefinitionWithUIConfig(entityDefinitionId)`
154
+
155
+ Получить EntityDefinition с полями и сгенерированной UI конфигурацией.
156
+
157
+ ```typescript
158
+ const config = await sdk.getEntityDefinitionWithUIConfig(entityDefinitionId);
159
+ // config: { entityDefinition, fields, uiConfig }
160
+ ```
161
+
162
+ ## 🔧 Типы
163
+
164
+ ```typescript
165
+ import type {
166
+ EntityDefinition,
167
+ Field,
168
+ EntityInstanceWithFields,
169
+ QueryParams,
170
+ CreateInstanceData,
171
+ UpdateInstanceData,
172
+ PaginationResult,
173
+ } from '@igorchugurov/public-api-sdk';
174
+ ```
175
+
176
+ ## 🛠️ Обработка ошибок
177
+
178
+ SDK использует типизированные ошибки:
179
+
180
+ ```typescript
181
+ import {
182
+ NotFoundError,
183
+ PermissionDeniedError,
184
+ ValidationError,
185
+ AuthenticationError,
186
+ SDKError,
187
+ } from '@igorchugurov/public-api-sdk';
188
+
189
+ try {
190
+ const instance = await sdk.getInstance(entityDefinitionId, id);
191
+ } catch (error) {
192
+ if (error instanceof NotFoundError) {
193
+ // 404 - экземпляр не найден
194
+ } else if (error instanceof PermissionDeniedError) {
195
+ // 403 - нет прав доступа
196
+ } else if (error instanceof ValidationError) {
197
+ // 400 - ошибка валидации
198
+ } else if (error instanceof AuthenticationError) {
199
+ // 401 - ошибка авторизации
200
+ }
201
+ }
202
+ ```
203
+
204
+ ## ⚙️ Кэширование
205
+
206
+ SDK поддерживает кэширование конфигурации для оптимизации:
207
+
208
+ ```typescript
209
+ const sdk = await createServerSDK(projectId, config, {
210
+ enableCache: true, // default: true
211
+ cacheTTL: 5 * 60 * 1000, // default: 5 минут
212
+ });
213
+ ```
214
+
215
+ ## 🚧 Разработка
216
+
217
+ ```bash
218
+ # Установка зависимостей
219
+ pnpm install
220
+
221
+ # Сборка
222
+ pnpm build
223
+
224
+ # Проверка типов
225
+ pnpm type-check
226
+
227
+ # Режим разработки (watch mode)
228
+ pnpm dev
229
+ ```
230
+
231
+ ## 📄 Лицензия
232
+
233
+ MIT
234
+