@igorchugurov/public-api-sdk 1.2.0 → 1.4.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 CHANGED
@@ -19,4 +19,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
22
-
package/README.md CHANGED
@@ -17,6 +17,7 @@ pnpm add @igorchugurov/public-api-sdk
17
17
  SDK предоставляет полный набор инструментов для работы с универсальными сущностями:
18
18
 
19
19
  ### 🔄 CRUD операции
20
+
20
21
  - **Получение списка** с расширенной фильтрацией, поиском и пагинацией
21
22
  - **Получение одного экземпляра** с автоматической загрузкой связей и файлов
22
23
  - **Создание** экземпляров с поддержкой relations и автоматической установкой `created_by`
@@ -24,6 +25,7 @@ SDK предоставляет полный набор инструментов
24
25
  - **Удаление** экземпляров с автоматической очисткой связей
25
26
 
26
27
  ### 🔗 Работа со связями (Relations)
28
+
27
29
  - Автоматическое определение relation-полей из конфигурации
28
30
  - Поддержка всех типов связей: `manyToMany`, `manyToOne`, `oneToMany`, `oneToOne`
29
31
  - Batch-загрузка связанных объектов для оптимизации производительности
@@ -31,33 +33,39 @@ SDK предоставляет полный набор инструментов
31
33
  - Опция получения relations как ID или полных объектов
32
34
 
33
35
  ### 🔍 Поиск и фильтрация
36
+
34
37
  - **Умный поиск** по полям с флагом `searchable: true`
35
38
  - **JSONB фильтрация** для обычных полей
36
39
  - **Relation фильтрация** с автоматическим определением relation-полей
37
40
  - **Гибкая сортировка** по любому полю с поддержкой `asc`/`desc`
38
41
 
39
42
  ### 📁 Работа с файлами
43
+
40
44
  - Автоматическая загрузка файлов и изображений для полей типа `files` и `images`
41
45
  - Batch-загрузка файлов для оптимизации запросов
42
46
  - Поддержка множественных файлов на поле
43
47
 
44
48
  ### ⚡ Производительность
49
+
45
50
  - **Кэширование конфигурации** EntityDefinition и Fields (TTL: 5 минут по умолчанию)
46
51
  - **Batch-запросы** для relations и файлов
47
52
  - **Оптимизированные RPC функции** для поиска и загрузки связей
48
53
  - Поддержка ESM и CJS форматов
49
54
 
50
55
  ### 🎯 Типобезопасность
56
+
51
57
  - Полная типизация всех методов и параметров
52
58
  - Экспорт всех типов для использования в вашем коде
53
59
  - Типизированные ошибки для удобной обработки
54
60
 
55
61
  ### 🔐 Безопасность
62
+
56
63
  - Интеграция с Supabase RLS (Row Level Security)
57
64
  - Автоматическая проверка прав доступа
58
65
  - Типизированные ошибки для различных сценариев доступа
59
66
 
60
67
  ### 🎨 UI конфигурация
68
+
61
69
  - Автоматическая генерация UI конфигурации из EntityDefinition и Fields
62
70
  - Поддержка кастомных UI настроек
63
71
  - Генерация конфигурации колонок таблицы из полей
@@ -67,8 +75,8 @@ SDK предоставляет полный набор инструментов
67
75
  ### 1. Server Component (SSR)
68
76
 
69
77
  ```typescript
70
- import { createServerSDK } from '@igorchugurov/public-api-sdk/server';
71
- import { cookies } from 'next/headers';
78
+ import { createServerSDK } from "@igorchugurov/public-api-sdk/server";
79
+ import { cookies } from "next/headers";
72
80
 
73
81
  export default async function MyPage({ params }) {
74
82
  const { projectId } = await params;
@@ -97,7 +105,7 @@ export default async function MyPage({ params }) {
97
105
  const { data, pagination } = await sdk.getInstances(entityDefinitionId, {
98
106
  page: 1,
99
107
  limit: 20,
100
- search: 'test',
108
+ search: "test",
101
109
  });
102
110
 
103
111
  return <div>{/* ... */}</div>;
@@ -107,9 +115,9 @@ export default async function MyPage({ params }) {
107
115
  ### 2. Client Component
108
116
 
109
117
  ```typescript
110
- 'use client';
118
+ "use client";
111
119
 
112
- import { createClientSDK } from '@igorchugurov/public-api-sdk';
120
+ import { createClientSDK } from "@igorchugurov/public-api-sdk";
113
121
 
114
122
  const sdk = createClientSDK(
115
123
  projectId,
@@ -157,14 +165,25 @@ const { data, pagination } = await sdk.getInstances(entityDefinitionId, {
157
165
  ```typescript
158
166
  const instance = await sdk.getInstance(entityDefinitionId, id, {
159
167
  relationsAsIds?: boolean; // default: false
168
+ loadFiles?: boolean; // default: false
160
169
  });
161
170
  ```
162
171
 
163
172
  **Пример:**
164
173
 
165
174
  ```typescript
175
+ // Базовое использование - без файлов
176
+ const instance = await sdk.getInstance("entity-def-id", "instance-id");
177
+
178
+ // Для редактирования - нужны только ID связей
166
179
  const instance = await sdk.getInstance("entity-def-id", "instance-id", {
167
- relationsAsIds: true, // для редактирования - нужны только ID
180
+ relationsAsIds: true,
181
+ });
182
+
183
+ // Для отображения с файлами - полные объекты
184
+ const instance = await sdk.getInstance("entity-def-id", "instance-id", {
185
+ relationsAsIds: false,
186
+ loadFiles: true, // файлы и изображения будут загружены как полные объекты EntityFile
168
187
  });
169
188
  ```
170
189
 
@@ -175,24 +194,41 @@ const instance = await sdk.getInstance("entity-def-id", "instance-id", {
175
194
  ```typescript
176
195
  const instance = await sdk.getInstanceBySlug(entityDefinitionId, slug, {
177
196
  relationsAsIds?: boolean; // default: false
197
+ loadFiles?: boolean; // default: false
178
198
  });
179
199
  ```
180
200
 
181
201
  **Пример:**
182
202
 
183
203
  ```typescript
184
- const instance = await sdk.getInstanceBySlug("entity-def-id", "my-article-slug", {
185
- relationsAsIds: false, // для отображения - нужны полные объекты
186
- });
204
+ // Базовое использование - без файлов
205
+ const instance = await sdk.getInstanceBySlug(
206
+ "entity-def-id",
207
+ "my-article-slug"
208
+ );
209
+
210
+ // Для отображения с файлами - полные объекты
211
+ const instance = await sdk.getInstanceBySlug(
212
+ "entity-def-id",
213
+ "my-article-slug",
214
+ {
215
+ relationsAsIds: false,
216
+ loadFiles: true, // файлы и изображения будут загружены как полные объекты EntityFile
217
+ }
218
+ );
187
219
  ```
188
220
 
189
221
  **Особенности:**
222
+
190
223
  - Валидирует формат slug перед запросом (только строчные латинские буквы, цифры и дефисы)
191
224
  - Работает аналогично `getInstance`, но ищет по slug вместо id
192
- - Поддерживает те же параметры, что и `getInstance` (relationsAsIds)
225
+ - Поддерживает те же параметры, что и `getInstance`
193
226
  - Параметр `relationsAsIds`:
194
227
  - `false` (по умолчанию) - возвращает полные объекты связанных сущностей
195
228
  - `true` - возвращает только массивы ID связанных сущностей
229
+ - Параметр `loadFiles`:
230
+ - `false` (по умолчанию) - файлы и изображения не загружаются
231
+ - `true` - файлы и изображения загружаются как полные объекты `EntityFile` (с `fileUrl`, `fileName`, `fileSize` и т.д.)
196
232
 
197
233
  #### `createInstance(entityDefinitionId, data)`
198
234
 
@@ -206,6 +242,7 @@ const instance = await sdk.createInstance(entityDefinitionId, {
206
242
  ```
207
243
 
208
244
  **Особенности:**
245
+
209
246
  - Автоматически генерирует уникальный `slug` из поля `name`
210
247
  - Если slug уже существует, добавляет случайный суффикс
211
248
  - Автоматически устанавливает `created_by` из текущего пользователя
@@ -270,7 +307,7 @@ import type {
270
307
  CreateInstanceData,
271
308
  UpdateInstanceData,
272
309
  PaginationResult,
273
- } from '@igorchugurov/public-api-sdk';
310
+ } from "@igorchugurov/public-api-sdk";
274
311
  ```
275
312
 
276
313
  ### Slug поддержка
@@ -308,7 +345,7 @@ import {
308
345
  ValidationError,
309
346
  AuthenticationError,
310
347
  SDKError,
311
- } from '@igorchugurov/public-api-sdk';
348
+ } from "@igorchugurov/public-api-sdk";
312
349
 
313
350
  try {
314
351
  const instance = await sdk.getInstance(entityDefinitionId, id);
@@ -355,4 +392,3 @@ pnpm dev
355
392
  ## 📄 Лицензия
356
393
 
357
394
  MIT
358
-
@@ -164,6 +164,8 @@ interface Field {
164
164
  selectorRelationId?: string | null;
165
165
  relationFieldName?: string | null;
166
166
  relationFieldLabel?: string | null;
167
+ relationFieldRequired?: boolean;
168
+ relationFieldRequiredText?: string | null;
167
169
  defaultStringValue?: string | null;
168
170
  defaultNumberValue?: number | null;
169
171
  defaultBooleanValue?: boolean | null;
@@ -177,6 +179,7 @@ interface Field {
177
179
  foreignKeyValue?: string | null;
178
180
  typeFieldName?: string | null;
179
181
  optionsFieldName?: string | null;
182
+ exclude?: string | null;
180
183
  acceptFileTypes?: string | null;
181
184
  maxFileSize?: number | null;
182
185
  maxFiles?: number | null;
@@ -1108,9 +1111,11 @@ declare abstract class BasePublicAPIClient {
1108
1111
  }>;
1109
1112
  abstract getInstance(entityDefinitionId: string, id: string, params?: {
1110
1113
  relationsAsIds?: boolean;
1114
+ loadFiles?: boolean;
1111
1115
  }): Promise<EntityInstanceWithFields>;
1112
1116
  abstract getInstanceBySlug(entityDefinitionId: string, slug: string, params?: {
1113
1117
  relationsAsIds?: boolean;
1118
+ loadFiles?: boolean;
1114
1119
  }): Promise<EntityInstanceWithFields>;
1115
1120
  abstract createInstance(entityDefinitionId: string, data: CreateInstanceData): Promise<EntityInstanceWithFields>;
1116
1121
  abstract updateInstance(entityDefinitionId: string, id: string, data: UpdateInstanceData): Promise<EntityInstanceWithFields>;
@@ -1149,17 +1154,24 @@ declare class PublicAPIClient extends BasePublicAPIClient {
1149
1154
  * Получить режим работы клиента (для отладки)
1150
1155
  */
1151
1156
  getMode(): "server" | "client";
1157
+ /**
1158
+ * Загружает файлы для экземпляра и возвращает их как полные объекты EntityFile,
1159
+ * сгруппированные по именам полей
1160
+ */
1161
+ private loadFilesForInstance;
1152
1162
  /**
1153
1163
  * Получить один экземпляр
1154
1164
  */
1155
1165
  getInstance(entityDefinitionId: string, id: string, params?: {
1156
1166
  relationsAsIds?: boolean;
1167
+ loadFiles?: boolean;
1157
1168
  }): Promise<EntityInstanceWithFields>;
1158
1169
  /**
1159
1170
  * Получить один экземпляр по slug
1160
1171
  */
1161
1172
  getInstanceBySlug(entityDefinitionId: string, slug: string, params?: {
1162
1173
  relationsAsIds?: boolean;
1174
+ loadFiles?: boolean;
1163
1175
  }): Promise<EntityInstanceWithFields>;
1164
1176
  /**
1165
1177
  * Получить список экземпляров
@@ -164,6 +164,8 @@ interface Field {
164
164
  selectorRelationId?: string | null;
165
165
  relationFieldName?: string | null;
166
166
  relationFieldLabel?: string | null;
167
+ relationFieldRequired?: boolean;
168
+ relationFieldRequiredText?: string | null;
167
169
  defaultStringValue?: string | null;
168
170
  defaultNumberValue?: number | null;
169
171
  defaultBooleanValue?: boolean | null;
@@ -177,6 +179,7 @@ interface Field {
177
179
  foreignKeyValue?: string | null;
178
180
  typeFieldName?: string | null;
179
181
  optionsFieldName?: string | null;
182
+ exclude?: string | null;
180
183
  acceptFileTypes?: string | null;
181
184
  maxFileSize?: number | null;
182
185
  maxFiles?: number | null;
@@ -1108,9 +1111,11 @@ declare abstract class BasePublicAPIClient {
1108
1111
  }>;
1109
1112
  abstract getInstance(entityDefinitionId: string, id: string, params?: {
1110
1113
  relationsAsIds?: boolean;
1114
+ loadFiles?: boolean;
1111
1115
  }): Promise<EntityInstanceWithFields>;
1112
1116
  abstract getInstanceBySlug(entityDefinitionId: string, slug: string, params?: {
1113
1117
  relationsAsIds?: boolean;
1118
+ loadFiles?: boolean;
1114
1119
  }): Promise<EntityInstanceWithFields>;
1115
1120
  abstract createInstance(entityDefinitionId: string, data: CreateInstanceData): Promise<EntityInstanceWithFields>;
1116
1121
  abstract updateInstance(entityDefinitionId: string, id: string, data: UpdateInstanceData): Promise<EntityInstanceWithFields>;
@@ -1149,17 +1154,24 @@ declare class PublicAPIClient extends BasePublicAPIClient {
1149
1154
  * Получить режим работы клиента (для отладки)
1150
1155
  */
1151
1156
  getMode(): "server" | "client";
1157
+ /**
1158
+ * Загружает файлы для экземпляра и возвращает их как полные объекты EntityFile,
1159
+ * сгруппированные по именам полей
1160
+ */
1161
+ private loadFilesForInstance;
1152
1162
  /**
1153
1163
  * Получить один экземпляр
1154
1164
  */
1155
1165
  getInstance(entityDefinitionId: string, id: string, params?: {
1156
1166
  relationsAsIds?: boolean;
1167
+ loadFiles?: boolean;
1157
1168
  }): Promise<EntityInstanceWithFields>;
1158
1169
  /**
1159
1170
  * Получить один экземпляр по slug
1160
1171
  */
1161
1172
  getInstanceBySlug(entityDefinitionId: string, slug: string, params?: {
1162
1173
  relationsAsIds?: boolean;
1174
+ loadFiles?: boolean;
1163
1175
  }): Promise<EntityInstanceWithFields>;
1164
1176
  /**
1165
1177
  * Получить список экземпляров
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { F as FieldConfig, a as FieldValue, E as EntityDefinition, b as Field, c as EntityUIConfig, C as ColumnConfig, S as SDKOptions, P as PublicAPIClient } from './client-DS5xnLAo.mjs';
2
- export { y as ActionConfig, A as AuthResult, g as CreateInstanceData, D as DbType, l as DbTypeToTSType, m as EntityData, e as EntityDefinitionConfig, x as EntityFile, n as EntityInstance, q as EntityInstanceWithFields, p as EntityRelation, k as FieldOption, j as FieldType, r as FilterValue, z as FormPageConfig, G as GetInstancesOptions, I as InstanceData, L as ListPageConfig, M as MessagesConfig, h as PaginationResult, w as PartialInstanceData, B as PartialUIConfig, d as ProjectConfig, Q as QueryParams, R as RelationFilterInfo, f as RelationFilterMode, o as RelationType, s as RelationsData, i as SignUpData, U as UpdateInstanceData, v as getFieldValue, u as isEntityData, t as isFieldValue } from './client-DS5xnLAo.mjs';
1
+ import { F as FieldConfig, a as FieldValue, E as EntityDefinition, b as Field, c as EntityUIConfig, C as ColumnConfig, S as SDKOptions, P as PublicAPIClient } from './client-BTvcDpY4.mjs';
2
+ export { y as ActionConfig, A as AuthResult, g as CreateInstanceData, D as DbType, l as DbTypeToTSType, m as EntityData, e as EntityDefinitionConfig, x as EntityFile, n as EntityInstance, q as EntityInstanceWithFields, p as EntityRelation, k as FieldOption, j as FieldType, r as FilterValue, z as FormPageConfig, G as GetInstancesOptions, I as InstanceData, L as ListPageConfig, M as MessagesConfig, h as PaginationResult, w as PartialInstanceData, B as PartialUIConfig, d as ProjectConfig, Q as QueryParams, R as RelationFilterInfo, f as RelationFilterMode, o as RelationType, s as RelationsData, i as SignUpData, U as UpdateInstanceData, v as getFieldValue, u as isEntityData, t as isFieldValue } from './client-BTvcDpY4.mjs';
3
3
  import '@supabase/supabase-js';
4
4
 
5
5
  /**
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { F as FieldConfig, a as FieldValue, E as EntityDefinition, b as Field, c as EntityUIConfig, C as ColumnConfig, S as SDKOptions, P as PublicAPIClient } from './client-DS5xnLAo.js';
2
- export { y as ActionConfig, A as AuthResult, g as CreateInstanceData, D as DbType, l as DbTypeToTSType, m as EntityData, e as EntityDefinitionConfig, x as EntityFile, n as EntityInstance, q as EntityInstanceWithFields, p as EntityRelation, k as FieldOption, j as FieldType, r as FilterValue, z as FormPageConfig, G as GetInstancesOptions, I as InstanceData, L as ListPageConfig, M as MessagesConfig, h as PaginationResult, w as PartialInstanceData, B as PartialUIConfig, d as ProjectConfig, Q as QueryParams, R as RelationFilterInfo, f as RelationFilterMode, o as RelationType, s as RelationsData, i as SignUpData, U as UpdateInstanceData, v as getFieldValue, u as isEntityData, t as isFieldValue } from './client-DS5xnLAo.js';
1
+ import { F as FieldConfig, a as FieldValue, E as EntityDefinition, b as Field, c as EntityUIConfig, C as ColumnConfig, S as SDKOptions, P as PublicAPIClient } from './client-BTvcDpY4.js';
2
+ export { y as ActionConfig, A as AuthResult, g as CreateInstanceData, D as DbType, l as DbTypeToTSType, m as EntityData, e as EntityDefinitionConfig, x as EntityFile, n as EntityInstance, q as EntityInstanceWithFields, p as EntityRelation, k as FieldOption, j as FieldType, r as FilterValue, z as FormPageConfig, G as GetInstancesOptions, I as InstanceData, L as ListPageConfig, M as MessagesConfig, h as PaginationResult, w as PartialInstanceData, B as PartialUIConfig, d as ProjectConfig, Q as QueryParams, R as RelationFilterInfo, f as RelationFilterMode, o as RelationType, s as RelationsData, i as SignUpData, U as UpdateInstanceData, v as getFieldValue, u as isEntityData, t as isFieldValue } from './client-BTvcDpY4.js';
3
3
  import '@supabase/supabase-js';
4
4
 
5
5
  /**
package/dist/index.js CHANGED
@@ -765,6 +765,22 @@ function flattenInstance(instance, fields, relationsAsIds = false) {
765
765
  }
766
766
  return result;
767
767
  }
768
+ function transformEntityFile(row) {
769
+ return {
770
+ id: row.id,
771
+ entityInstanceId: row.entity_instance_id,
772
+ fieldId: row.field_id,
773
+ fileUrl: row.file_url,
774
+ filePath: row.file_path,
775
+ fileName: row.file_name,
776
+ fileSize: row.file_size,
777
+ fileType: row.file_type,
778
+ storageBucket: row.storage_bucket,
779
+ uploadedBy: row.uploaded_by,
780
+ createdAt: row.created_at,
781
+ updatedAt: row.updated_at
782
+ };
783
+ }
768
784
 
769
785
  // src/client.ts
770
786
  init_slug();
@@ -797,6 +813,42 @@ var _PublicAPIClient = class _PublicAPIClient extends BasePublicAPIClient {
797
813
  getMode() {
798
814
  return this.mode;
799
815
  }
816
+ /**
817
+ * Загружает файлы для экземпляра и возвращает их как полные объекты EntityFile,
818
+ * сгруппированные по именам полей
819
+ */
820
+ async loadFilesForInstance(instanceId, fileFields) {
821
+ if (fileFields.length === 0) {
822
+ return /* @__PURE__ */ new Map();
823
+ }
824
+ const { data: allFiles, error: filesError } = await this.supabase.from("entity_file").select("*").eq("entity_instance_id", instanceId);
825
+ if (filesError) {
826
+ throw new SDKError(
827
+ "FILES_LOAD_ERROR",
828
+ `Failed to load files for instance ${instanceId}: ${filesError.message}`,
829
+ 500,
830
+ filesError
831
+ );
832
+ }
833
+ if (!allFiles || allFiles.length === 0) {
834
+ return /* @__PURE__ */ new Map();
835
+ }
836
+ const filesMap = /* @__PURE__ */ new Map();
837
+ const fieldIdToName = new Map(
838
+ fileFields.map((f) => [f.id, f.name])
839
+ );
840
+ allFiles.forEach((fileRow) => {
841
+ if (!fileRow.field_id) return;
842
+ const fieldName = fieldIdToName.get(fileRow.field_id);
843
+ if (!fieldName) return;
844
+ const entityFile = transformEntityFile(fileRow);
845
+ if (!filesMap.has(fieldName)) {
846
+ filesMap.set(fieldName, []);
847
+ }
848
+ filesMap.get(fieldName).push(entityFile);
849
+ });
850
+ return filesMap;
851
+ }
800
852
  /**
801
853
  * Получить один экземпляр
802
854
  */
@@ -873,34 +925,15 @@ var _PublicAPIClient = class _PublicAPIClient extends BasePublicAPIClient {
873
925
  }
874
926
  }
875
927
  }
876
- const fileFields = fields.filter(
877
- (f) => f.type === "files" || f.type === "images"
878
- );
879
- if (fileFields.length > 0) {
880
- const { data: allFiles, error: filesError } = await this.supabase.from("entity_file").select("id, field_id").eq("entity_instance_id", id);
881
- if (filesError) {
882
- throw new SDKError(
883
- "FILES_LOAD_ERROR",
884
- `Failed to load files for instance ${id}: ${filesError.message}`,
885
- 500,
886
- filesError
887
- );
888
- }
889
- if (allFiles) {
890
- const filesByFieldId = /* @__PURE__ */ new Map();
891
- allFiles.forEach((file) => {
892
- if (file.field_id) {
893
- if (!filesByFieldId.has(file.field_id)) {
894
- filesByFieldId.set(file.field_id, []);
895
- }
896
- filesByFieldId.get(file.field_id).push(file.id);
897
- }
898
- });
928
+ if ((params == null ? void 0 : params.loadFiles) === true) {
929
+ const fileFields = fields.filter(
930
+ (f) => f.type === "files" || f.type === "images"
931
+ );
932
+ if (fileFields.length > 0) {
933
+ const filesMap = await this.loadFilesForInstance(id, fileFields);
899
934
  fileFields.forEach((field) => {
900
- const fileIds = filesByFieldId.get(field.id) || [];
901
- if (fileIds.length > 0 || !transformedInstance.data[field.name]) {
902
- transformedInstance.data[field.name] = fileIds;
903
- }
935
+ const files = filesMap.get(field.name) || [];
936
+ transformedInstance.data[field.name] = files;
904
937
  });
905
938
  }
906
939
  }
@@ -1001,34 +1034,18 @@ var _PublicAPIClient = class _PublicAPIClient extends BasePublicAPIClient {
1001
1034
  }
1002
1035
  }
1003
1036
  }
1004
- const fileFields = fields.filter(
1005
- (f) => f.type === "files" || f.type === "images"
1006
- );
1007
- if (fileFields.length > 0) {
1008
- const { data: allFiles, error: filesError } = await this.supabase.from("entity_file").select("id, field_id").eq("entity_instance_id", transformedInstance.id);
1009
- if (filesError) {
1010
- throw new SDKError(
1011
- "FILES_LOAD_ERROR",
1012
- `Failed to load files for instance with slug ${slug}: ${filesError.message}`,
1013
- 500,
1014
- filesError
1037
+ if ((params == null ? void 0 : params.loadFiles) === true) {
1038
+ const fileFields = fields.filter(
1039
+ (f) => f.type === "files" || f.type === "images"
1040
+ );
1041
+ if (fileFields.length > 0) {
1042
+ const filesMap = await this.loadFilesForInstance(
1043
+ transformedInstance.id,
1044
+ fileFields
1015
1045
  );
1016
- }
1017
- if (allFiles) {
1018
- const filesByFieldId = /* @__PURE__ */ new Map();
1019
- allFiles.forEach((file) => {
1020
- if (file.field_id) {
1021
- if (!filesByFieldId.has(file.field_id)) {
1022
- filesByFieldId.set(file.field_id, []);
1023
- }
1024
- filesByFieldId.get(file.field_id).push(file.id);
1025
- }
1026
- });
1027
1046
  fileFields.forEach((field) => {
1028
- const fileIds = filesByFieldId.get(field.id) || [];
1029
- if (fileIds.length > 0 || !transformedInstance.data[field.name]) {
1030
- transformedInstance.data[field.name] = fileIds;
1031
- }
1047
+ const files = filesMap.get(field.name) || [];
1048
+ transformedInstance.data[field.name] = files;
1032
1049
  });
1033
1050
  }
1034
1051
  }