@palmares/schemas 0.1.21 → 0.1.23

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