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