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