@palmares/schemas 0.1.20 → 0.1.22

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.
Files changed (111) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/cjs/src/adapter/index.js +2 -0
  3. package/dist/cjs/src/conf.js +3 -4
  4. package/dist/cjs/src/model.js +34 -38
  5. package/dist/cjs/src/schema/array.js +1 -0
  6. package/dist/cjs/src/schema/object.js +2 -8
  7. package/dist/cjs/src/schema/schema.js +1 -0
  8. package/dist/cjs/src/utils.js +12 -14
  9. package/dist/cjs/src/validators/utils.js +1 -0
  10. package/dist/cjs/tsconfig.types.tsbuildinfo +1 -1
  11. package/dist/cjs/types/adapter/index.d.ts +2 -0
  12. package/dist/cjs/types/adapter/index.d.ts.map +1 -1
  13. package/dist/cjs/types/conf.d.ts +3 -0
  14. package/dist/cjs/types/conf.d.ts.map +1 -1
  15. package/dist/cjs/types/domain.d.ts +3 -0
  16. package/dist/cjs/types/domain.d.ts.map +1 -1
  17. package/dist/cjs/types/model.d.ts +2 -2
  18. package/dist/cjs/types/model.d.ts.map +1 -1
  19. package/dist/cjs/types/schema/array.d.ts +1 -0
  20. package/dist/cjs/types/schema/array.d.ts.map +1 -1
  21. package/dist/cjs/types/schema/object.d.ts.map +1 -1
  22. package/dist/cjs/types/schema/schema.d.ts +1 -0
  23. package/dist/cjs/types/schema/schema.d.ts.map +1 -1
  24. package/dist/cjs/types/utils.d.ts +2 -1
  25. package/dist/cjs/types/utils.d.ts.map +1 -1
  26. package/dist/cjs/types/validators/utils.d.ts +1 -0
  27. package/dist/cjs/types/validators/utils.d.ts.map +1 -1
  28. package/dist/esm/src/adapter/index.js +2 -0
  29. package/dist/esm/src/conf.js +3 -4
  30. package/dist/esm/src/model.js +32 -30
  31. package/dist/esm/src/schema/array.js +1 -0
  32. package/dist/esm/src/schema/object.js +2 -1
  33. package/dist/esm/src/schema/schema.js +1 -0
  34. package/dist/esm/src/utils.js +9 -6
  35. package/dist/esm/src/validators/utils.js +1 -0
  36. package/package.json +11 -5
  37. package/.turbo/turbo-build$colon$watch.log +0 -24
  38. package/.turbo/turbo-build.log +0 -4
  39. package/.turbo/turbo-build:watch.log +0 -26
  40. package/__tests__/.drizzle/migrations/0000_skinny_harrier.sql +0 -22
  41. package/__tests__/.drizzle/migrations/meta/0000_snapshot.json +0 -156
  42. package/__tests__/.drizzle/migrations/meta/_journal.json +0 -13
  43. package/__tests__/.drizzle/schema.ts +0 -35
  44. package/__tests__/drizzle.config.ts +0 -11
  45. package/__tests__/eslint.config.js +0 -10
  46. package/__tests__/manage.ts +0 -5
  47. package/__tests__/node_modules/.bin/drizzle-kit +0 -17
  48. package/__tests__/node_modules/.bin/tsc +0 -17
  49. package/__tests__/node_modules/.bin/tsserver +0 -17
  50. package/__tests__/node_modules/.bin/tsx +0 -17
  51. package/__tests__/package.json +0 -34
  52. package/__tests__/sqlite.db +0 -0
  53. package/__tests__/src/core/array.test.ts +0 -131
  54. package/__tests__/src/core/boolean.test.ts +0 -66
  55. package/__tests__/src/core/datetime.test.ts +0 -102
  56. package/__tests__/src/core/index.ts +0 -35
  57. package/__tests__/src/core/model.test.ts +0 -260
  58. package/__tests__/src/core/models.ts +0 -50
  59. package/__tests__/src/core/numbers.test.ts +0 -177
  60. package/__tests__/src/core/object.test.ts +0 -218
  61. package/__tests__/src/core/string.test.ts +0 -222
  62. package/__tests__/src/core/test.test.ts +0 -59
  63. package/__tests__/src/core/types.test.ts +0 -97
  64. package/__tests__/src/core/union.test.ts +0 -99
  65. package/__tests__/src/settings.ts +0 -69
  66. package/__tests__/tsconfig.json +0 -11
  67. package/src/adapter/fields/array.ts +0 -31
  68. package/src/adapter/fields/boolean.ts +0 -43
  69. package/src/adapter/fields/datetime.ts +0 -43
  70. package/src/adapter/fields/index.ts +0 -72
  71. package/src/adapter/fields/number.ts +0 -43
  72. package/src/adapter/fields/object.ts +0 -52
  73. package/src/adapter/fields/string.ts +0 -43
  74. package/src/adapter/fields/union.ts +0 -43
  75. package/src/adapter/index.ts +0 -35
  76. package/src/adapter/types.ts +0 -276
  77. package/src/compile.ts +0 -14
  78. package/src/conf.ts +0 -27
  79. package/src/constants.ts +0 -7
  80. package/src/domain.ts +0 -15
  81. package/src/exceptions.ts +0 -17
  82. package/src/index.ts +0 -318
  83. package/src/middleware.ts +0 -52
  84. package/src/model.ts +0 -507
  85. package/src/parsers/convert-from-number.ts +0 -13
  86. package/src/parsers/convert-from-string.ts +0 -19
  87. package/src/parsers/index.ts +0 -2
  88. package/src/schema/array.ts +0 -824
  89. package/src/schema/boolean.ts +0 -792
  90. package/src/schema/datetime.ts +0 -704
  91. package/src/schema/index.ts +0 -5
  92. package/src/schema/number.ts +0 -929
  93. package/src/schema/object.ts +0 -798
  94. package/src/schema/schema.ts +0 -1178
  95. package/src/schema/string.ts +0 -941
  96. package/src/schema/types.ts +0 -154
  97. package/src/schema/union.ts +0 -724
  98. package/src/types.ts +0 -66
  99. package/src/utils.ts +0 -383
  100. package/src/validators/array.ts +0 -183
  101. package/src/validators/boolean.ts +0 -52
  102. package/src/validators/datetime.ts +0 -121
  103. package/src/validators/number.ts +0 -178
  104. package/src/validators/object.ts +0 -56
  105. package/src/validators/schema.ts +0 -142
  106. package/src/validators/string.ts +0 -278
  107. package/src/validators/types.ts +0 -1
  108. package/src/validators/union.ts +0 -52
  109. package/src/validators/utils.ts +0 -225
  110. package/tsconfig.json +0 -9
  111. package/tsconfig.types.json +0 -10
package/src/model.ts DELETED
@@ -1,507 +0,0 @@
1
- import {
2
- AutoField,
3
- BigAutoField,
4
- BooleanField,
5
- CharField,
6
- DateField,
7
- DecimalField,
8
- EnumField,
9
- type Field,
10
- ForeignKeyField,
11
- IntegerField,
12
- type InternalModelClass_DoNotUse,
13
- type Model,
14
- type ModelFields,
15
- TextField,
16
- TranslatableField,
17
- UuidField
18
- } from '@palmares/databases';
19
-
20
- import { TranslatableFieldNotImplementedError } from './exceptions';
21
- import { number } from './schema';
22
- import { ArraySchema } from './schema/array';
23
- import { boolean } from './schema/boolean';
24
- import { datetime } from './schema/datetime';
25
- import { ObjectSchema } from './schema/object';
26
- import { Schema } from './schema/schema';
27
- import { string } from './schema/string';
28
- import { union } from './schema/union';
29
-
30
- import type { DefinitionsOfSchemaType, ExtractTypeFromObjectOfSchemas } from './schema/types';
31
-
32
- async function getSchemaFromModelField(
33
- model: ReturnType<typeof Model>,
34
- field: Field<any, any, any, any, any, any, any, any>,
35
- parent: Schema<any, any> | undefined,
36
- definedFields: Record<any, Schema<any, DefinitionsOfSchemaType>> | undefined,
37
- engineInstanceName?: string,
38
- options?: {
39
- foreignKeyRelation?: {
40
- schema?: Schema<any, any>;
41
- isArray: boolean;
42
- model: ReturnType<typeof Model>;
43
- fieldToSearchOnModel: string;
44
- fieldToGetFromData: string;
45
- relationOrRelatedName: string;
46
- };
47
- }
48
- ) {
49
- let schema: Schema<any, any> | undefined = undefined;
50
- if (field instanceof AutoField || field instanceof BigAutoField) schema = number().integer().optional();
51
- else if (field instanceof DecimalField)
52
- schema = number().decimalPlaces(field.decimalPlaces).maxDigits(field.maxDigits);
53
- else if (field instanceof IntegerField) schema = number().integer();
54
- else if (field instanceof BooleanField) schema = boolean();
55
- else if (field instanceof TextField || field instanceof CharField || field instanceof UuidField) {
56
- schema = string();
57
- if (field.allowBlank === false) schema = (schema as ReturnType<typeof string>).minLength(1);
58
- if (field instanceof CharField && typeof field.maxLength === 'number')
59
- schema = (schema as ReturnType<typeof string>).maxLength(field.maxLength);
60
- if (field instanceof UuidField) {
61
- schema = (schema as ReturnType<typeof string>).uuid();
62
- if (field.autoGenerate) schema = (schema as ReturnType<typeof string>).optional();
63
- }
64
- } else if (field instanceof DateField) {
65
- schema = datetime().allowString();
66
- if (field.autoNow || field.autoNowAdd) schema = (schema as ReturnType<typeof datetime>).optional();
67
- } else if (field instanceof EnumField) {
68
- const allChoicesOfTypeStrings = field.choices.filter((choice: any) => typeof choice === 'string');
69
- const allChoicesOfTypeNumbers = field.choices.filter((choice: any) => typeof choice === 'number');
70
-
71
- let schemaForChoicesAsStrings: Schema<any, any> | undefined = undefined;
72
- let schemaForChoicesAsNumbers: Schema<any, any> | undefined = undefined;
73
- if (allChoicesOfTypeStrings.length > 0) schemaForChoicesAsStrings = string().is([...allChoicesOfTypeStrings]);
74
- if (allChoicesOfTypeNumbers.length > 0) schemaForChoicesAsNumbers = number().is([...allChoicesOfTypeNumbers]);
75
- if (schemaForChoicesAsStrings && schemaForChoicesAsNumbers)
76
- schema = union([schemaForChoicesAsStrings, schemaForChoicesAsNumbers]);
77
- else if (schemaForChoicesAsStrings) schema = schemaForChoicesAsStrings;
78
- else if (schemaForChoicesAsNumbers) schema = schemaForChoicesAsNumbers;
79
- } else if (field instanceof ForeignKeyField) {
80
- const doesADefinedFieldExistWithRelatedName =
81
- parent && field.relatedName && (parent as any).__data?.[field.relatedName];
82
- const doesADefinedFieldExistWithRelationName =
83
- definedFields && field.relationName && definedFields[field.relationName];
84
- const fieldWithRelatedName = doesADefinedFieldExistWithRelatedName
85
- ? (parent as any).__data?.[field.relatedName]
86
- : undefined;
87
- const fieldWithRelationName = doesADefinedFieldExistWithRelationName
88
- ? definedFields[field.relationName]
89
- : undefined;
90
- const isFieldWithRelatedNameAModelField =
91
- fieldWithRelatedName instanceof Schema && (fieldWithRelatedName as any).__model !== undefined;
92
- const isFieldWithRelationNameAModelField =
93
- fieldWithRelationName instanceof Schema && (fieldWithRelationName as any).__model !== undefined;
94
- const relatedToModel = field.relatedTo;
95
- const toField = field.toField;
96
- if (Object.keys(model._initialized).length > 0) {
97
- const engineInstance = await model.default.getEngineInstance(engineInstanceName);
98
- const relatedToModelInstance = engineInstance.__modelsOfEngine[relatedToModel];
99
- const modelFieldsOfRelatedModel = (relatedToModelInstance as any).__cachedFields[toField];
100
- if (isFieldWithRelatedNameAModelField) {
101
- if (typeof options !== 'object') options = {};
102
- options.foreignKeyRelation = {
103
- schema: parent,
104
- isArray: fieldWithRelatedName instanceof ArraySchema,
105
- model: (fieldWithRelatedName as any).__model,
106
- fieldToSearchOnModel: field.fieldName,
107
- fieldToGetFromData: field.toField,
108
- relationOrRelatedName: field.relatedName!
109
- };
110
- } else if (isFieldWithRelationNameAModelField) {
111
- if (typeof options !== 'object') options = {};
112
- options.foreignKeyRelation = {
113
- isArray: fieldWithRelationName instanceof ArraySchema,
114
- model: (fieldWithRelationName as any).__model,
115
- fieldToSearchOnModel: field.toField,
116
- fieldToGetFromData: field.fieldName,
117
- relationOrRelatedName: field.relationName!
118
- };
119
- }
120
-
121
- return getSchemaFromModelField(
122
- relatedToModelInstance,
123
- modelFieldsOfRelatedModel,
124
- parent,
125
- definedFields,
126
- engineInstanceName,
127
- options
128
- );
129
- }
130
- } else if (field instanceof TranslatableField && field.customAttributes.schema) {
131
- if (field.customAttributes.schema instanceof Schema === false)
132
- throw new TranslatableFieldNotImplementedError(field.fieldName);
133
- schema = field.customAttributes.schema;
134
- }
135
-
136
- if (field.allowNull && schema) schema = schema.nullable().optional();
137
- if (field.defaultValue && schema) schema = schema.default(field.defaultValue);
138
-
139
- return schema || string();
140
- }
141
-
142
- /**
143
- * Different from other schemas, this function is a factory function that returns either an ObjectSchema or an
144
- * ArraySchema. The idea is to build the schema of a model dynamically based on its fields.
145
- *
146
- * Another feature is that it can automatically add the foreign key relation to the schema, but for that you need to
147
- * define the fields of the related model in the fields object.
148
- *
149
- * For example: A User model have a field `companyId` that is a ForeignKeyField to the Company model. The `relationName`
150
- * is the direct relation from the User model to the Company model, and the `relatedName` is the reverse relation from
151
- * the Company model to the User model. If you define the fieldName as either the relatedName or the relationName it
152
- * will fetch the data automatically.
153
- *
154
- * **Important**: We build the schema dynamically but also lazily, if you don't try to parse or validate the schema, it
155
- * won't be built. After the first time it's built, it's cached and never built again.
156
- *
157
- * **Important 2**: If you want to use the automatic relation feature, you need to define guarantee that the foreignKey
158
- * field fieldName exists on `show` array, or that it doesn't exist on `omit` array.
159
- *
160
- * Like: `{ options: { show: ['id', 'name', 'companyId'] }}` or `{ options: { omit: ['id'] }}` it **will work**.
161
- *
162
- * If you do `{ options: { show: ['id', 'name'] }}` or `{ options: { omit: ['companyId']} }` it **won't work**.
163
- *
164
- * **Important 3**: If you want to return an array instead of an object, you need to pass the `many` option as true.
165
- *
166
- * @example
167
- * ```typescript
168
- * import { auto, choice, foreignKey, Model, define } from '@palmares/databases';
169
- * import * as p from '@palmares/schemas';
170
- *
171
- * const Company = define('Company', {
172
- * fields: {
173
- * id: auto(),
174
- * name: text(),
175
- * },
176
- * options: {
177
- * tableName: 'company',
178
- * }
179
- * });
180
- *
181
- * class User extends Model<User>() {
182
- * fields = {
183
- * id: auto(),
184
- * type: choice({ choices: ['user', 'admin'] }),
185
- * companyId: foreignKey({
186
- * relatedTo: Company,
187
- * relationName: 'company',
188
- * relatedName: 'usersOfCompany',
189
- * toField: 'id',
190
- * onDelete: 'CASCADE',
191
- * }),
192
- * }
193
- *
194
- * options = {
195
- * tableName: 'user',
196
- * }
197
- * }
198
- *
199
- * const userSchema = p.modelSchema(User, {
200
- * fields: {
201
- * company: p.modelSchema(Company).optional({ outputOnly: true });
202
- * },
203
- * show: ['type', 'companyId'], // 'companyId' is required for the automatic relation to work, otherwise it won't show
204
- * omitRelation: ['company']
205
- * });
206
- *
207
- * const companySchema = p.modelSchema(Company, {
208
- * fields: {
209
- * usersOfCompany: p.modelSchema(User, { many: true }).optional({ outputOnly: true });
210
- * },
211
- * // The `companyId` field on the 'User' model is tied to the `id` field on the 'Company' model so 'id' is required.
212
- * show: ['id', 'type'] * });
213
- *```
214
- * @param model - The model that you want to build the schema from.
215
- * @param options - The options to build the schema.
216
- * @param options.ignoreExtraneousFields - If you want to ignore extraneous fields set this to true.
217
- * @param options.engineInstance - What engine instance you want to use to fetch the data. Defaults to the first one.
218
- * @param options.omitRelation - Fields that you want to omit from the relation. For example, on the example above, on
219
- * the `userSchema` you can omit the `companyId` field from the relation by just passing `['company']`, on the
220
- * `companySchema` you can omit the `id` field from company by passing `['usersOfCompany']`.
221
- *
222
- * @param options.fields - Extra fields that you want to add to the schema. If it has the same name as the model field,
223
- * We will not create a schema for that field and use the one you have defined here.
224
- * @param options.omit - Fields that you want to omit from the schema. If that is defined, we ignore `show` option.
225
- * @param options.show - Fields that you want to show on the schema. If that is defined, we ignore `omit` option.
226
- * @param options.many - If you want to return an array instead of an object, set this to true. With that we create
227
- * an ArraySchema instead of an ObjectSchema.
228
- *
229
- * @returns - If you pass the `many` option as true, we return an ArraySchema, otherwise we return an ObjectSchema.
230
- */
231
- export function modelSchema<
232
- TModel extends ReturnType<typeof Model>,
233
- const TOmit extends readonly (keyof ModelFields<InstanceType<TModel>>)[] | undefined[] = undefined[],
234
- const TShow extends readonly (keyof ModelFields<InstanceType<TModel>>)[] | undefined[] = undefined[],
235
- TMany extends boolean = false,
236
- TFields extends Record<any, Schema<any, DefinitionsOfSchemaType>> | undefined = undefined,
237
- TAllModelFields = ModelFields<InstanceType<TModel>>,
238
- TDefinitionsOfSchemaType extends DefinitionsOfSchemaType = DefinitionsOfSchemaType,
239
- TFieldsOnModel = TOmit extends undefined[]
240
- ? TShow extends undefined[]
241
- ? TAllModelFields
242
- : Pick<TAllModelFields, TShow[number] extends keyof TAllModelFields ? TShow[number] : never>
243
- : Omit<TAllModelFields, TOmit[number] extends keyof TAllModelFields ? TOmit[number] : never>,
244
- TReturnType extends {
245
- input: any;
246
- output: any;
247
- validate: any;
248
- internal: any;
249
- representation: any;
250
- } = {
251
- input: TFields extends undefined
252
- ? TFieldsOnModel
253
- : Omit<
254
- TFieldsOnModel,
255
- keyof ExtractTypeFromObjectOfSchemas<
256
- // eslint-disable-next-line ts/ban-types
257
- TFields extends undefined ? {} : TFields,
258
- 'input'
259
- >
260
- > &
261
- ExtractTypeFromObjectOfSchemas<
262
- // eslint-disable-next-line ts/ban-types
263
- TFields extends undefined ? {} : TFields,
264
- 'input'
265
- >;
266
- output: TFields extends undefined
267
- ? TFieldsOnModel
268
- : Omit<
269
- TFieldsOnModel,
270
- keyof ExtractTypeFromObjectOfSchemas<
271
- // eslint-disable-next-line ts/ban-types
272
- TFields extends undefined ? {} : TFields,
273
- 'output'
274
- >
275
- > &
276
- ExtractTypeFromObjectOfSchemas<
277
- // eslint-disable-next-line ts/ban-types
278
- TFields extends undefined ? {} : TFields,
279
- 'output'
280
- >;
281
- internal: TFields extends undefined
282
- ? TFieldsOnModel
283
- : Omit<
284
- TFieldsOnModel,
285
- keyof ExtractTypeFromObjectOfSchemas<
286
- // eslint-disable-next-line ts/ban-types
287
- TFields extends undefined ? {} : TFields,
288
- 'internal'
289
- >
290
- > &
291
- ExtractTypeFromObjectOfSchemas<
292
- // eslint-disable-next-line ts/ban-types
293
- TFields extends undefined ? {} : TFields,
294
- 'internal'
295
- >;
296
- representation: TFields extends undefined
297
- ? TFieldsOnModel
298
- : Omit<
299
- TFieldsOnModel,
300
- keyof ExtractTypeFromObjectOfSchemas<
301
- // eslint-disable-next-line ts/ban-types
302
- TFields extends Record<any, Schema<any, DefinitionsOfSchemaType>> ? TFields : {},
303
- 'representation'
304
- >
305
- > &
306
- ExtractTypeFromObjectOfSchemas<
307
- // eslint-disable-next-line ts/ban-types
308
- TFields extends Record<any, Schema<any, DefinitionsOfSchemaType>> ? TFields : {},
309
- 'representation'
310
- >;
311
- validate: TFields extends undefined
312
- ? TFieldsOnModel
313
- : Omit<
314
- TFieldsOnModel,
315
- keyof ExtractTypeFromObjectOfSchemas<
316
- // eslint-disable-next-line ts/ban-types
317
- TFields extends Record<any, Schema<any, DefinitionsOfSchemaType>> ? TFields : {},
318
- 'validate'
319
- >
320
- > &
321
- ExtractTypeFromObjectOfSchemas<
322
- // eslint-disable-next-line ts/ban-types
323
- TFields extends Record<any, Schema<any, DefinitionsOfSchemaType>> ? TFields : {},
324
- 'validate'
325
- >;
326
- }
327
- >(
328
- model: TModel,
329
- options?: {
330
- ignoreExtraneousFields?: boolean;
331
- engineInstance?: string;
332
- fields?: TFields;
333
- omit?: TOmit;
334
- show?: TShow;
335
- omitRelation?: readonly (keyof TFields)[];
336
- many?: TMany;
337
- }
338
- ): TMany extends true
339
- ? ArraySchema<
340
- {
341
- input: TReturnType['input'][];
342
- output: TReturnType['output'][];
343
- internal: TReturnType['internal'][];
344
- representation: TReturnType['representation'][];
345
- validate: TReturnType['validate'][];
346
- },
347
- TDefinitionsOfSchemaType,
348
- [
349
- ObjectSchema<
350
- {
351
- input: TReturnType['input'];
352
- output: TReturnType['output'];
353
- internal: TReturnType['internal'];
354
- representation: TReturnType['representation'];
355
- validate: TReturnType['validate'];
356
- },
357
- TDefinitionsOfSchemaType,
358
- Record<any, any>
359
- >
360
- ]
361
- >
362
- : ObjectSchema<
363
- {
364
- input: TReturnType['input'];
365
- output: TReturnType['output'];
366
- internal: TReturnType['internal'];
367
- representation: TReturnType['representation'];
368
- validate: TReturnType['validate'];
369
- },
370
- TDefinitionsOfSchemaType,
371
- Record<any, any>
372
- > {
373
- const lazyModelSchema = ObjectSchema.new({} as any) as ObjectSchema<any, any, any> & {
374
- __runBeforeParseAndData: Required<Schema<any, any>['__runBeforeParseAndData']>;
375
- };
376
- const parentSchema = options?.many === true ? ArraySchema.new([lazyModelSchema]) : (lazyModelSchema as any);
377
- const omitRelationAsSet = new Set(options?.omitRelation || []);
378
- const omitAsSet = new Set(options?.omit || []);
379
- const showAsSet = new Set(options?.show || []);
380
- const fieldsAsObject = options?.fields || {};
381
- const customFieldValues = Object.values(fieldsAsObject);
382
-
383
- // We need to add it to the instance to be able to access it on the `toRepresentation` callback
384
- (lazyModelSchema as any).__omitRelation = omitRelationAsSet;
385
- parentSchema.__model = model;
386
- (lazyModelSchema as any).__model = model;
387
-
388
- // Add this callback to transform the model fields
389
- parentSchema.__runBeforeParseAndData = async () => {
390
- const promise = new Promise((resolve) => {
391
- const fieldsOfModels = (model as unknown as typeof InternalModelClass_DoNotUse)._fields();
392
- const fieldsAsEntries = Object.entries(fieldsOfModels);
393
- const fieldsWithAutomaticRelations = new Map<
394
- Schema<any, any>,
395
- {
396
- relationOrRelatedName: string;
397
- isArray: boolean;
398
- model: ReturnType<typeof Model>;
399
- fieldToSearchOnModel: string;
400
- fieldToGetFromData: string;
401
- }[]
402
- >();
403
-
404
- const fields = fieldsAsObject as Record<any, Schema<any, any>>;
405
- Promise.all(
406
- fieldsAsEntries.map(async ([key, value]) => {
407
- if (omitAsSet.has(key as any)) return;
408
- if (showAsSet.size > 0 && !showAsSet.has(key as any)) return;
409
-
410
- let schema = (fieldsAsObject as any)[key as any];
411
- const optionsForForeignKeyRelation: any = {};
412
- if (!schema || value instanceof ForeignKeyField) {
413
- const newSchema = await getSchemaFromModelField(
414
- model,
415
- value,
416
- parentSchema?.__getParent?.(),
417
- options?.fields,
418
- options?.engineInstance,
419
- optionsForForeignKeyRelation
420
- );
421
- if (!schema) schema = newSchema;
422
- }
423
-
424
- // Appends the foreign key relation to the schema automatically.
425
- if (optionsForForeignKeyRelation.foreignKeyRelation) {
426
- const rootSchema = optionsForForeignKeyRelation?.foreignKeyRelation?.schema || lazyModelSchema;
427
- const existingRelations =
428
- fieldsWithAutomaticRelations.get(rootSchema) ||
429
- ([] as {
430
- relationOrRelatedName: string;
431
- isArray: boolean;
432
- model: ReturnType<typeof Model>;
433
- fieldToSearchOnModel: string;
434
- fieldToGetFromData: string;
435
- }[]);
436
- existingRelations.push({
437
- relationOrRelatedName: optionsForForeignKeyRelation.foreignKeyRelation.relationOrRelatedName,
438
- isArray: optionsForForeignKeyRelation.foreignKeyRelation.isArray,
439
- model: optionsForForeignKeyRelation.foreignKeyRelation.model,
440
- fieldToSearchOnModel: optionsForForeignKeyRelation.foreignKeyRelation.fieldToSearchOnModel,
441
- fieldToGetFromData: optionsForForeignKeyRelation.foreignKeyRelation.fieldToGetFromData
442
- });
443
- fieldsWithAutomaticRelations.set(rootSchema, existingRelations);
444
- }
445
-
446
- (fieldsAsObject as any)[key] = schema;
447
- return fieldsAsObject;
448
- })
449
- ).then(async () => {
450
- if (fieldsWithAutomaticRelations.size > 0) {
451
- // This way we can get all of the relations concurrently with Promise.all
452
- for (const [schema, relations] of fieldsWithAutomaticRelations.entries()) {
453
- schema.toRepresentation(
454
- async (data: any | any[]) => {
455
- const allData = Array.isArray(data) ? data : [data];
456
- // since we are changing the data by reference, just return the data itself.
457
- await Promise.all(
458
- allData.map(async (data) =>
459
- Promise.all(
460
- relations.map(async (relation) => {
461
- // Ignore if the data of the relation already exists
462
- if (relation.relationOrRelatedName in data) return;
463
-
464
- let relationData: any | any[] = await relation.model.default.get({
465
- search: {
466
- [relation.fieldToSearchOnModel]: data[relation.fieldToGetFromData]
467
- }
468
- });
469
- if (relation.isArray !== true) relationData = relationData[0];
470
- data[relation.relationOrRelatedName] = relationData;
471
-
472
- if ((schema as any).__omitRelation.has(relation.relationOrRelatedName as any))
473
- delete data[relation.fieldToGetFromData];
474
- })
475
- )
476
- )
477
- );
478
-
479
- return data;
480
- },
481
- {
482
- after: true
483
- }
484
- );
485
- }
486
- }
487
-
488
- (lazyModelSchema as any).__data = fields as any;
489
-
490
- await Promise.all(
491
- customFieldValues.map(async (schema: any) => {
492
- schema['__getParent'] = () => lazyModelSchema;
493
- if (schema['__runBeforeParseAndData']) await schema['__runBeforeParseAndData'](schema);
494
- })
495
- );
496
- resolve(undefined);
497
- });
498
- });
499
- if (parentSchema.__alreadyAppliedModel) return parentSchema.__alreadyAppliedModel;
500
- parentSchema.__alreadyAppliedModel = promise;
501
- return promise;
502
- };
503
-
504
- if (options?.ignoreExtraneousFields !== true) lazyModelSchema.removeExtraneous();
505
-
506
- return parentSchema;
507
- }
@@ -1,13 +0,0 @@
1
- import type { Schema } from '../schema/schema';
2
-
3
- /**
4
- * This will convert a value from a number to any other type.
5
- *
6
- * @param callback
7
- * @returns
8
- */
9
- export function convertFromNumberBuilder(
10
- callback: (value: number) => Awaited<ReturnType<Parameters<Schema['__parsers']['high']['set']>[1]>>
11
- ) {
12
- return (value: any) => callback(value);
13
- }
@@ -1,19 +0,0 @@
1
- import type { Schema } from '../schema/schema';
2
-
3
- /**
4
- * This will convert a value from a string to any other type.
5
- *
6
- * @param callback
7
- * @returns
8
- */
9
- export function convertFromStringBuilder(
10
- callback: (value: string) => Awaited<ReturnType<Parameters<Schema['__parsers']['high']['set']>[1]>>
11
- ): Parameters<Schema['__parsers']['high']['set']>[1] {
12
- return (value: any) => {
13
- if (typeof value === 'string') return callback(value);
14
- return {
15
- value,
16
- preventNextParsers: false
17
- };
18
- };
19
- }
@@ -1,2 +0,0 @@
1
- export { convertFromNumberBuilder } from './convert-from-number';
2
- export { convertFromStringBuilder } from './convert-from-string';