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