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