@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
@@ -1,824 +0,0 @@
1
- import { Schema } from './schema';
2
- import {
3
- defaultTransform,
4
- defaultTransformToAdapter,
5
- shouldRunDataOnComplexSchemas,
6
- transformSchemaAndCheckIfShouldBeHandledByFallbackOnComplexSchemas
7
- } from '../utils';
8
- import { arrayValidation, maxLength, minLength, nonEmpty } from '../validators/array';
9
- import { nullable, optional } from '../validators/schema';
10
- import { Validator } from '../validators/utils';
11
-
12
- import type { DefinitionsOfSchemaType, ExtractTypeFromArrayOfSchemas } from './types';
13
-
14
- export class ArraySchema<
15
- TType extends {
16
- input: any;
17
- validate: any;
18
- internal: any;
19
- output: any;
20
- representation: any;
21
- } = {
22
- input: any[];
23
- output: any[];
24
- internal: any[];
25
- representation: any[];
26
- validate: any[];
27
- },
28
- TDefinitions extends DefinitionsOfSchemaType = DefinitionsOfSchemaType,
29
- TSchemas extends readonly [Schema, ...Schema[]] | [[Schema]] = [[Schema]]
30
- > extends Schema<TType, TDefinitions> {
31
- protected fieldType = 'array';
32
-
33
- protected __schemas: readonly [Schema, ...Schema[]] | [[Schema]];
34
-
35
- protected __type: {
36
- message: string;
37
- check: (value: TType['input']) => boolean;
38
- } = {
39
- message: 'Invalid type',
40
- check: (value) => Array.isArray(value)
41
- };
42
-
43
- protected __minLength!: {
44
- value: number;
45
- inclusive: boolean;
46
- message: string;
47
- };
48
-
49
- protected __maxLength!: {
50
- value: number;
51
- inclusive: boolean;
52
- message: string;
53
- };
54
-
55
- protected __nonEmpty!: {
56
- message: string;
57
- };
58
-
59
- constructor(...schemas: TSchemas) {
60
- super();
61
- this.__schemas = schemas;
62
- }
63
-
64
- protected async __transformToAdapter(options: Parameters<Schema['__transformToAdapter']>[0]): Promise<any> {
65
- return defaultTransformToAdapter(
66
- async (adapter) => {
67
- const schemas = Array.isArray(this.__schemas[0]) ? this.__schemas[0] : this.__schemas;
68
- const transformedSchemasAsString: string[] = [];
69
- const transformedSchemas = [] as unknown as [any, ...any[]] | [any];
70
- let shouldBeHandledByFallback = false;
71
-
72
- await Promise.all(
73
- (schemas as unknown as Schema[]).map(async (schema) => {
74
- const [transformedData, shouldAddFallbackValidationForThisSchema] =
75
- await transformSchemaAndCheckIfShouldBeHandledByFallbackOnComplexSchemas(schema, options);
76
-
77
- if (shouldAddFallbackValidationForThisSchema) shouldBeHandledByFallback = true;
78
-
79
- for (const transformedSchema of transformedData) {
80
- transformedSchemasAsString.push(transformedSchema.asString);
81
- transformedSchemas.push(transformedSchema.transformed);
82
- }
83
- })
84
- );
85
-
86
- // eslint-disable-next-line ts/no-unnecessary-condition
87
- if (shouldBeHandledByFallback)
88
- Validator.createAndAppendFallback(
89
- this,
90
- arrayValidation(
91
- Array.isArray(this.__schemas[0]) === false,
92
- (Array.isArray(this.__schemas[0]) ? this.__schemas[0] : this.__schemas) as unknown as Schema<any, any>[]
93
- )
94
- );
95
-
96
- return defaultTransform(
97
- 'array',
98
- this,
99
- adapter,
100
- adapter.array,
101
- () => ({
102
- isTuple: Array.isArray(this.__schemas[0]) === false,
103
- nullable: this.__nullable,
104
- optional: this.__optional,
105
- maxLength: this.__maxLength,
106
- minLength: this.__minLength,
107
- nonEmpty: this.__nonEmpty,
108
- schemas: transformedSchemas,
109
- type: this.__type,
110
- parsers: {
111
- nullable: this.__nullable.allow,
112
- optional: this.__optional.allow
113
- }
114
- }),
115
- {
116
- optional,
117
- nullable,
118
- minLength,
119
- maxLength,
120
- nonEmpty
121
- },
122
- {
123
- shouldAddStringVersion: options.shouldAddStringVersion,
124
- // eslint-disable-next-line ts/require-await
125
- fallbackIfNotSupported: async () => []
126
- }
127
- );
128
- },
129
- this,
130
- this.__transformedSchemas,
131
- options,
132
- 'array'
133
- );
134
- }
135
-
136
- /**
137
- * This let's you refine the schema with custom validations. This is useful when you want to validate something that
138
- * is not supported by default by the schema adapter.
139
- *
140
- * @example
141
- * ```typescript
142
- * import * as p from '@palmares/schemas';
143
- *
144
- * const numberSchema = p.number().refine((value) => {
145
- * if (value < 0) return { code: 'invalid_number', message: 'The number should be greater than 0' };
146
- * });
147
- *
148
- * const { errors, parsed } = await numberSchema.parse(-1);
149
- *
150
- * // [{ isValid: false, code: 'invalid_number', message: 'The number should be greater than 0', path: [] }]
151
- * console.log(errors);
152
- * ```
153
- *
154
- * @param refinementCallback - The callback that will be called to validate the value.
155
- * @param options - Options for the refinement.
156
- * @param options.isAsync - Whether the callback is async or not. Defaults to true.
157
- */
158
- refine(
159
- refinementCallback: (
160
- value: TType['input']
161
- ) =>
162
- | Promise<void | undefined | { code: string; message: string }>
163
- | void
164
- | undefined
165
- | { code: string; message: string }
166
- ) {
167
- return super.refine(refinementCallback) as unknown as ArraySchema<
168
- {
169
- input: TType['input'];
170
- validate: TType['validate'];
171
- internal: TType['internal'];
172
- output: TType['output'];
173
- representation: TType['representation'];
174
- },
175
- TDefinitions,
176
- TSchemas
177
- >;
178
- }
179
-
180
- /**
181
- * Allows the value to be either undefined or null. Different from the `optional` method on other schemas, You can
182
- * pass `outputOnly` as `true` to this method.
183
- * This will allow you to pass `null` or `undefined` as a value on the {@link Schema.data} method, but it will not
184
- * allow the value to be `null` or `undefined`. This is useful for typing purposes.
185
- *
186
- * @example
187
- * ```typescript
188
- * import * as p from '@palmares/schemas';
189
- *
190
- * const numberSchema = p.number().optional();
191
- *
192
- * const { errors, parsed } = await numberSchema.parse(undefined);
193
- *
194
- * console.log(parsed); // undefined
195
- *
196
- * const { errors, parsed } = await numberSchema.parse(null);
197
- *
198
- * console.log(parsed); // null
199
- *
200
- * const { errors, parsed } = await numberSchema.parse(1);
201
- *
202
- * console.log(parsed); // 1
203
- *
204
- * const companySchema = p.object({ id: p.number(), name: p.string() });
205
- * const userSchema = p.object({
206
- * id: p.number(),
207
- * name: p.string(),
208
- * company: companySchema.optional({ outputOnly: true })
209
- * });
210
- *
211
- * // Will not allow the company to be null or undefined on a typing level.
212
- * const { errors, parsed } = await userSchema.data({ id: 1, name: 'John Doe' });
213
- * // Will allow the company to be null or undefined on a typing level
214
- * const value = await userSchema.data({ id: 1, name: 'John Doe' });
215
- * ```
216
- *
217
- * @returns - The schema we are working with.
218
- */
219
- optional<TOutputOnly extends boolean = false>(options?: {
220
- message?: string;
221
- allow?: false;
222
- outputOnly?: TOutputOnly;
223
- }) {
224
- return (options?.outputOnly ? this : super.optional(options)) as unknown as ArraySchema<
225
- TOutputOnly extends true
226
- ? {
227
- input: TType['input'];
228
- validate: TType['validate'];
229
- internal: TType['internal'];
230
- output: TType['output'] | undefined | null;
231
- representation: TType['representation'];
232
- }
233
- : {
234
- input: TType['input'] | undefined | null;
235
- validate: TType['validate'] | undefined | null;
236
- internal: TType['internal'] | undefined | null;
237
- output: TType['output'] | undefined | null;
238
- representation: TType['representation'] | undefined | null;
239
- },
240
- TDefinitions,
241
- TSchemas
242
- >;
243
- }
244
-
245
- /**
246
- * Just adds a message when the value is undefined. It's just a syntax sugar for
247
- *
248
- * ```typescript
249
- * p.datetime().optional({ message: 'This value should be defined', allow: false })
250
- * ```
251
- *
252
- * @param options - The options of nonOptional function
253
- * @param options.message - A custom message if the value is undefined.
254
- *
255
- * @returns - The schema.
256
- */
257
- nonOptional(options?: { message: string }) {
258
- return super.optional({
259
- message: options?.message,
260
- allow: false
261
- }) as unknown as ArraySchema<
262
- {
263
- input: TType['input'];
264
- validate: TType['validate'];
265
- internal: TType['internal'];
266
- output: TType['output'];
267
- representation: TType['representation'];
268
- },
269
- TDefinitions
270
- >;
271
- }
272
-
273
- /**
274
- * Allows the value to be null and ONLY null. You can also use this function to set a custom message when the value
275
- * is NULL by setting the { message: 'Your custom message', allow: false } on the options.
276
- *
277
- * @example
278
- * ```typescript
279
- * import * as p from '@palmares/schemas';
280
- *
281
- * const numberSchema = p.number().nullable();
282
- *
283
- * const { errors, parsed } = await numberSchema.parse(null);
284
- *
285
- * console.log(parsed); // null
286
- *
287
- * const { errors, parsed } = await numberSchema.parse(undefined);
288
- *
289
- * console.log(errors); // [{ isValid: false, code: 'invalid_type', message: 'Invalid type', path: [] }]
290
- * ```
291
- *
292
- * @param options - The options for the nullable function.
293
- * @param options.message - The message to be shown when the value is not null. Defaults to 'Cannot be null'.
294
- * @param options.allow - Whether the value can be null or not. Defaults to true.
295
- *
296
- * @returns The schema.
297
- */
298
- nullable(options?: { message: string; allow: false }) {
299
- return super.nullable(options) as unknown as ArraySchema<
300
- {
301
- input: TType['input'] | null;
302
- validate: TType['validate'] | null;
303
- internal: TType['internal'] | null;
304
- output: TType['output'] | null;
305
- representation: TType['representation'] | null;
306
- },
307
- TDefinitions,
308
- TSchemas
309
- >;
310
- }
311
-
312
- /**
313
- * Just adds a message when the value is null. It's just a syntax sugar for
314
- *
315
- * ```typescript
316
- * p.datetime().nullable({ message: 'This value cannot be null', allow: false })
317
- * ```
318
- *
319
- * @param options - The options of nonNullable function
320
- * @param options.message - A custom message if the value is null.
321
- *
322
- * @returns - The schema.
323
- */
324
- nonNullable(options?: { message: string }) {
325
- return super.nullable({
326
- message: options?.message || '',
327
- allow: false
328
- }) as unknown as ArraySchema<
329
- {
330
- input: TType['input'];
331
- validate: TType['validate'];
332
- internal: TType['internal'];
333
- output: TType['output'];
334
- representation: TType['representation'];
335
- },
336
- TDefinitions
337
- >;
338
- }
339
-
340
- /**
341
- * This method will remove the value from the representation of the schema. If the value is undefined it will keep
342
- * that way otherwise it will set the value to undefined after it's validated.
343
- * This is used in conjunction with the {@link data} function, the {@link parse} function or {@link validate}
344
- * function. This will remove the value from the representation of the schema.
345
- *
346
- * By default, the value will be removed just from the representation, in other words, when you call the {@link data}
347
- * function. But if you want to remove the value from the internal representation, you can pass the argument
348
- * `toInternal` as true. Then if you still want to remove the value from the representation, you will need to pass
349
- * the argument `toRepresentation` as true as well.
350
- *
351
- * @example
352
- * ```typescript
353
- * import * as p from '@palmares/schemas';
354
- *
355
- * const userSchema = p.object({
356
- * id: p.number().optional(),
357
- * name: p.string(),
358
- * password: p.string().omit()
359
- * });
360
- *
361
- * const user = await userSchema.data({
362
- * id: 1,
363
- * name: 'John Doe',
364
- * password: '123456'
365
- * });
366
- *
367
- * console.log(user); // { id: 1, name: 'John Doe' }
368
- * ```
369
- *
370
- *
371
- * @param args - By default, the value will be removed just from the representation, in other words, when you call
372
- * the {@link data} function.
373
- * But if you want to remove the value from the internal representation, you can pass the argument `toInternal`
374
- * as true.
375
- * Then if you still want to remove the value from the representation, you will need to pass the argument
376
- * `toRepresentation` as true as well.
377
- *
378
- * @returns The schema.
379
- */
380
- omit<
381
- TToInternal extends boolean,
382
- TToRepresentation extends boolean = boolean extends TToInternal ? true : false
383
- >(args?: { toInternal?: TToInternal; toRepresentation?: TToRepresentation }) {
384
- return super.omit(args) as unknown as ArraySchema<
385
- {
386
- input: TToInternal extends true ? TType['input'] | undefined : TType['input'];
387
- validate: TToInternal extends true ? TType['validate'] | undefined : TType['validate'];
388
- internal: TToInternal extends true ? undefined : TType['internal'];
389
- output: TToRepresentation extends true ? TType['output'] | undefined : TType['output'];
390
- representation: TToRepresentation extends true ? undefined : TType['representation'];
391
- },
392
- TDefinitions,
393
- TSchemas
394
- >;
395
- }
396
-
397
- /**
398
- * This function is used in conjunction with the {@link validate} function. It's used to save a value to an external
399
- * source like a database. You should always return the schema after you save the value, that way we will always have
400
- * the correct type of the schema after the save operation.
401
- *
402
- * You can use the {@link toRepresentation} function to transform and clean the value it returns after the save.
403
- *
404
- * @example
405
- * ```typescript
406
- * import * as p from '@palmares/schemas';
407
- *
408
- * import { User } from './models';
409
- *
410
- * const userSchema = p.object({
411
- * id: p.number().optional(),
412
- * name: p.string(),
413
- * email: p.string().email(),
414
- * }).onSave(async (value) => {
415
- * // Create or update the user on the database using palmares models or any other library of your choice.
416
- * if (value.id)
417
- * await User.default.set(value, { search: { id: value.id } });
418
- * else
419
- * await User.default.set(value);
420
- *
421
- * return value;
422
- * });
423
- *
424
- *
425
- * // Then, on your controller, do something like this:
426
- * const { isValid, save, errors } = await userSchema.validate(req.body);
427
- * if (isValid) {
428
- * const savedValue = await save();
429
- * return Response.json(savedValue, { status: 201 });
430
- * }
431
- *
432
- * return Response.json({ errors }, { status: 400 });
433
- * ```
434
- *
435
- * @param callback - The callback that will be called to save the value on an external source.
436
- *
437
- * @returns The schema.
438
- */
439
- onSave(
440
- callback: <TContext = any>(
441
- value: TType['internal'],
442
- context: TContext
443
- ) => Promise<TType['output']> | TType['output']
444
- ) {
445
- return super.onSave(callback) as unknown as ArraySchema<
446
- {
447
- input: TType['input'];
448
- validate: TType['validate'];
449
- internal: TType['internal'];
450
- output: TType['output'];
451
- representation: TType['representation'];
452
- },
453
- TDefinitions & {
454
- hasSave: true;
455
- },
456
- TSchemas
457
- >;
458
- }
459
-
460
- /**
461
- * This function is used to add a default value to the schema. If the value is either undefined or null, the default
462
- * value will be used.
463
- *
464
- * @example
465
- * ```typescript
466
- * import * as p from '@palmares/schemas';
467
- *
468
- * const numberSchema = p.number().default(0);
469
- *
470
- * const { errors, parsed } = await numberSchema.parse(undefined);
471
- *
472
- * console.log(parsed); // 0
473
- * ```
474
- */
475
- default<TDefaultValue extends TType['input'] | (() => Promise<TType['input']>)>(
476
- defaultValueOrFunction: TDefaultValue
477
- ) {
478
- return super.default(defaultValueOrFunction) as unknown as ArraySchema<
479
- {
480
- input: TType['input'] | undefined | null;
481
- validate: TType['validate'];
482
- internal: TType['internal'];
483
- output: TType['output'] | undefined | null;
484
- representation: TType['representation'];
485
- },
486
- TDefinitions,
487
- TSchemas
488
- >;
489
- }
490
-
491
- /**
492
- * This function is used to transform the value to the representation without validating it.
493
- * This is useful when you want to return a data from a query directly to the user. But for example
494
- * you are returning the data of a user, you can clean the password or any other sensitive data.
495
- *
496
- * @example
497
- * ```typescript
498
- * import * as p from '@palmares/schemas';
499
- *
500
- * const userSchema = p.object({
501
- * id: p.number().optional(),
502
- * name: p.string(),
503
- * email: p.string().email(),
504
- * password: p.string().optional()
505
- * }).toRepresentation(async (value) => {
506
- * return {
507
- * id: value.id,
508
- * name: value.name,
509
- * email: value.email
510
- * }
511
- * });
512
- *
513
- * const user = await userSchema.data({
514
- * id: 1,
515
- * name: 'John Doe',
516
- * email: 'john@gmail.com',
517
- * password: '123456'
518
- * });
519
- * ```
520
- */
521
- async data(value: TType['output']): Promise<TType['representation']> {
522
- let parsedValue = await super.data(value);
523
- if (Array.isArray(parsedValue)) {
524
- parsedValue = (await Promise.all(
525
- Array.isArray(this.__schemas[0])
526
- ? parsedValue.map((value: any) => {
527
- const schema = (this.__schemas as unknown as [[Schema]])[0][0];
528
-
529
- return shouldRunDataOnComplexSchemas(schema) ? schema.data(value) : value;
530
- })
531
- : (this.__schemas as [Schema, ...Schema[]]).map(async (schema) => {
532
- return shouldRunDataOnComplexSchemas(schema) ? schema.data(value) : value;
533
- })
534
- )) as unknown as TType['representation'];
535
- }
536
- return parsedValue;
537
- }
538
-
539
- /**
540
- * This function let's you customize the schema your own way. After we translate the schema on the adapter we call
541
- * this function to let you customize the custom schema your own way. Our API does not support passthrough?
542
- * No problem, you can use this function to customize the zod schema.
543
- *
544
- * @example
545
- * ```typescript
546
- * import * as p from '@palmares/schemas';
547
- *
548
- * const numberSchema = p.number().extends((schema) => {
549
- * return schema.nonnegative();
550
- * });
551
- *
552
- * const { errors, parsed } = await numberSchema.parse(-1);
553
- *
554
- * // [{ isValid: false, code: 'nonnegative', message: 'The number should be nonnegative', path: [] }]
555
- * console.log(errors);
556
- * ```
557
- *
558
- * @param callback - The callback that will be called to customize the schema.
559
- * @param toStringCallback - The callback that will be called to transform the schema to a string when you want to
560
- * compile the underlying schema to a string so you can save it for future runs.
561
- *
562
- * @returns The schema.
563
- */
564
- extends(
565
- callback: (
566
- schema: Awaited<ReturnType<NonNullable<TDefinitions['schemaAdapter']['object']>['translate']>>
567
- ) => Awaited<ReturnType<NonNullable<TDefinitions['schemaAdapter']['field']>['translate']>> | any,
568
- toStringCallback?: (schemaAsString: string) => string
569
- ) {
570
- return super.extends(callback, toStringCallback);
571
- }
572
-
573
- /**
574
- * This function is used to transform the value to the representation of the schema. When using the {@link data}
575
- * function. With this function you have full control to add data cleaning for example, transforming the data and
576
- * whatever. Another use case is when you want to return deeply nested recursive data.
577
- * The schema maps to itself.
578
- *
579
- * @example
580
- * ```typescript
581
- * import * as p from '@palmares/schemas';
582
- *
583
- * const recursiveSchema = p.object({
584
- * id: p.number().optional(),
585
- * name: p.string(),
586
- * }).toRepresentation(async (value) => {
587
- * return {
588
- * id: value.id,
589
- * name: value.name,
590
- * children: await Promise.all(value.children.map(async (child) => await recursiveSchema.data(child)))
591
- * }
592
- * });
593
- *
594
- * const data = await recursiveSchema.data({
595
- * id: 1,
596
- * name: 'John Doe',
597
- * });
598
- * ```
599
- *
600
- * @example
601
- * ```
602
- * import * as p from '@palmares/schemas';
603
- *
604
- * const colorToRGBSchema = p.string().toRepresentation(async (value) => {
605
- * switch (value) {
606
- * case 'red': return { r: 255, g: 0, b: 0 };
607
- * case 'green': return { r: 0, g: 255, b: 0 };
608
- * case 'blue': return { r: 0, g: 0, b: 255 };
609
- * default: return { r: 0, g: 0, b: 0 };
610
- * }
611
- * });
612
- * ```
613
- * @param toRepresentationCallback - The callback that will be called to transform the value to the representation.
614
- *
615
- * @returns The schema with a new return type
616
- */
617
- toRepresentation<TRepresentation>(
618
- toRepresentationCallback: (value: TType['representation']) => Promise<TRepresentation>
619
- ) {
620
- return super.toRepresentation(toRepresentationCallback) as unknown as ArraySchema<
621
- {
622
- input: TType['input'];
623
- validate: TType['validate'];
624
- internal: TType['internal'];
625
- output: TType['output'];
626
- representation: TRepresentation;
627
- },
628
- TDefinitions,
629
- TSchemas
630
- >;
631
- }
632
-
633
- /**
634
- * This function is used to transform the value to the internal representation of the schema. This is useful when you
635
- * want to transform the value to a type that the schema adapter can understand. For example, you might want to
636
- * transform a string to a date. This is the function you use.
637
- *
638
- * @example
639
- * ```typescript
640
- * import * as p from '@palmares/schemas';
641
- *
642
- * const dateSchema = p.string().toInternal((value) => {
643
- * return new Date(value);
644
- * });
645
- *
646
- * const date = await dateSchema.parse('2021-01-01');
647
- *
648
- * console.log(date); // Date object
649
- *
650
- * const rgbToColorSchema = p.object({
651
- * r: p.number().min(0).max(255),
652
- * g: p.number().min(0).max(255),
653
- * b: p.number().min(0).max(255),
654
- * }).toInternal(async (value) => {
655
- * if (value.r === 255 && value.g === 0 && value.b === 0) return 'red';
656
- * if (value.r === 0 && value.g === 255 && value.b === 0) return 'green';
657
- * if (value.r === 0 && value.g === 0 && value.b === 255) return 'blue';
658
- * return `rgb(${value.r}, ${value.g}, ${value.b})`;
659
- * });
660
- * ```
661
- *
662
- * @param toInternalCallback - The callback that will be called to transform the value to the internal representation.
663
- *
664
- * @returns The schema with a new return type.
665
- */
666
- toInternal<TInternal>(toInternalCallback: (value: TType['validate']) => Promise<TInternal>) {
667
- return super.toInternal(toInternalCallback) as unknown as ArraySchema<
668
- {
669
- input: TType['input'];
670
- validate: TType['validate'];
671
- internal: TInternal;
672
- output: TType['output'];
673
- representation: TType['representation'];
674
- },
675
- TDefinitions,
676
- TSchemas
677
- >;
678
- }
679
-
680
- /**
681
- * Called before the validation of the schema. Let's say that you want to validate a date that might receive a string,
682
- * you can convert that string to a date here BEFORE the validation. This pretty much transforms the value to a type
683
- * that the schema adapter can understand.
684
- *
685
- * @example
686
- * ```
687
- * import * as p from '@palmares/schemas';
688
- * import * as z from 'zod';
689
- *
690
- * const customRecordToMapSchema = p.schema().appendSchema(z.map()).toValidate(async (value) => {
691
- * return new Map(value); // Before validating we transform the value to a map.
692
- * });
693
- *
694
- * const { errors, parsed } = await customRecordToMapSchema.parse({ key: 'value' });
695
- * ```
696
- *
697
- * @param toValidateCallback - The callback that will be called to validate the value.
698
- *
699
- * @returns The schema with a new return type.
700
- */
701
- toValidate<TValidate>(toValidateCallback: (value: TType['input']) => Promise<TValidate> | TValidate) {
702
- return super.toValidate(toValidateCallback) as unknown as ArraySchema<
703
- {
704
- input: TType['input'];
705
- validate: TValidate;
706
- internal: TType['internal'];
707
- output: TType['output'];
708
- representation: TType['representation'];
709
- },
710
- TDefinitions,
711
- TSchemas
712
- >;
713
- }
714
-
715
- minLength(value: number, options?: Omit<ArraySchema['__minLength'], 'value'>) {
716
- const message = options?.message || `The array must have a minimum length of ${value}`;
717
- this.__minLength = {
718
- value: value,
719
- inclusive: typeof options?.inclusive === 'boolean' ? options.inclusive : true,
720
- message: message
721
- };
722
-
723
- return this as unknown as ArraySchema<
724
- {
725
- input: [TType['input'][number], ...TType['input'][number][]];
726
- validate: [TType['validate'][number], ...TType['validate'][number][]];
727
- internal: [TType['internal'][number], ...TType['internal'][number][]];
728
- output: [TType['output'][number], ...TType['output'][number][]];
729
- representation: [TType['representation'][number], ...TType['representation'][number][]];
730
- },
731
- TDefinitions,
732
- TSchemas
733
- >;
734
- }
735
-
736
- maxLength(value: number, options?: Omit<ArraySchema['__maxLength'], 'value'>) {
737
- const message = options?.message || `The array must have a maximum length of ${value}`;
738
- this.__maxLength = {
739
- value: value,
740
- inclusive: typeof options?.inclusive === 'boolean' ? options.inclusive : true,
741
- message: message
742
- };
743
-
744
- return this;
745
- }
746
-
747
- static new<
748
- TSchemas extends readonly [Schema, ...Schema[]] | [[Schema]],
749
- TDefinitions extends DefinitionsOfSchemaType = DefinitionsOfSchemaType
750
- >(
751
- ...schemas: TSchemas
752
- ): TSchemas extends [[Schema]]
753
- ? ArraySchema<
754
- {
755
- input: ExtractTypeFromArrayOfSchemas<TSchemas, 'input'>;
756
- validate: ExtractTypeFromArrayOfSchemas<TSchemas, 'validate'>;
757
- internal: ExtractTypeFromArrayOfSchemas<TSchemas, 'internal'>;
758
- output: ExtractTypeFromArrayOfSchemas<TSchemas, 'output'>;
759
- representation: ExtractTypeFromArrayOfSchemas<TSchemas, 'representation'>;
760
- },
761
- TDefinitions,
762
- TSchemas
763
- >
764
- : ArraySchema<
765
- {
766
- input: ExtractTypeFromArrayOfSchemas<TSchemas, 'input'>;
767
- validate: ExtractTypeFromArrayOfSchemas<TSchemas, 'validate'>;
768
- internal: ExtractTypeFromArrayOfSchemas<TSchemas, 'internal'>;
769
- output: ExtractTypeFromArrayOfSchemas<TSchemas, 'output'>;
770
- representation: ExtractTypeFromArrayOfSchemas<TSchemas, 'representation'>;
771
- },
772
- TDefinitions,
773
- TSchemas
774
- > & {
775
- maxLength: never;
776
- minLength: never;
777
- } {
778
- const returnValue = new ArraySchema<
779
- {
780
- input: ExtractTypeFromArrayOfSchemas<TSchemas, 'input'>;
781
- validate: ExtractTypeFromArrayOfSchemas<TSchemas, 'validate'>;
782
- internal: ExtractTypeFromArrayOfSchemas<TSchemas, 'internal'>;
783
- output: ExtractTypeFromArrayOfSchemas<TSchemas, 'output'>;
784
- representation: ExtractTypeFromArrayOfSchemas<TSchemas, 'representation'>;
785
- },
786
- TDefinitions,
787
- TSchemas
788
- >(...schemas);
789
-
790
- return returnValue as TSchemas extends [[Schema]]
791
- ? ArraySchema<
792
- {
793
- input: ExtractTypeFromArrayOfSchemas<TSchemas, 'input'>;
794
- validate: ExtractTypeFromArrayOfSchemas<TSchemas, 'validate'>;
795
- internal: ExtractTypeFromArrayOfSchemas<TSchemas, 'internal'>;
796
- output: ExtractTypeFromArrayOfSchemas<TSchemas, 'output'>;
797
- representation: ExtractTypeFromArrayOfSchemas<TSchemas, 'representation'>;
798
- },
799
- TDefinitions,
800
- TSchemas
801
- >
802
- : ArraySchema<
803
- {
804
- input: ExtractTypeFromArrayOfSchemas<TSchemas, 'input'>;
805
- validate: ExtractTypeFromArrayOfSchemas<TSchemas, 'validate'>;
806
- internal: ExtractTypeFromArrayOfSchemas<TSchemas, 'internal'>;
807
- output: ExtractTypeFromArrayOfSchemas<TSchemas, 'output'>;
808
- representation: ExtractTypeFromArrayOfSchemas<TSchemas, 'representation'>;
809
- },
810
- TDefinitions,
811
- TSchemas
812
- > & {
813
- maxLength: never;
814
- minLength: never;
815
- };
816
- }
817
- }
818
-
819
- export const array = <
820
- TSchemas extends readonly [Schema, ...Schema[]] | [[Schema]],
821
- TDefinitions extends DefinitionsOfSchemaType
822
- >(
823
- ...schemas: TSchemas
824
- ) => ArraySchema.new<TSchemas, TDefinitions>(...schemas);