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