|
1 | 1 | import { number, union, object, optional, parse, safeParse, string, type InferInput, type InferOutput, pipe, transform } from 'valibot'
|
2 |
| -import { checkUserA, checkUserB, checkUserC } from './utils.ts' |
| 2 | +import { checkUserA, checkUserB, checkUserC, nbIterations } from './utils.ts' |
3 | 3 |
|
4 |
| -const userSchema = object({ |
5 |
| - name: string(), |
6 |
| - age: optional(number(), 42), |
7 |
| - phone: pipe( |
8 |
| - optional(union([string(), number()]), "123-456-7890"), |
9 |
| - transform((phone) => typeof phone === 'number' ? phone.toString() : phone) |
10 |
| - ), |
11 |
| -}) |
| 4 | +const startTime = performance.now() |
12 | 5 |
|
13 |
| -export type User = InferOutput<typeof userSchema> |
| 6 | +for (let i = 0; i < nbIterations; i++) { |
14 | 7 |
|
15 |
| -export type UserInput = InferInput<typeof userSchema> |
| 8 | + const userSchema = object({ |
| 9 | + name: string(), |
| 10 | + age: optional(number(), 42), |
| 11 | + phone: pipe( |
| 12 | + optional(union([string(), number()]), "123-456-7890"), |
| 13 | + transform((phone) => typeof phone === 'number' ? phone.toString() : phone) |
| 14 | + ), |
| 15 | + }) |
16 | 16 |
|
17 |
| -const userA = parse(userSchema, { name: "Jordan" }) |
18 |
| -checkUserA(userA) |
| 17 | + // @ts-expect-error not exported, it's ok :p |
| 18 | + type User = InferOutput<typeof userSchema> |
19 | 19 |
|
20 |
| -function createUser (input: UserInput) { |
21 |
| - const result = safeParse(userSchema, input) |
22 |
| - if (!result.success) return userA |
23 |
| - return result.output |
24 |
| -} |
| 20 | + type UserInput = InferInput<typeof userSchema> |
| 21 | + |
| 22 | + const userA = parse(userSchema, { name: "Jordan" }) |
| 23 | + checkUserA(userA) |
| 24 | + |
| 25 | + function createUser (input: UserInput) { |
| 26 | + const result = safeParse(userSchema, input) |
| 27 | + if (!result.success) return userA |
| 28 | + return result.output |
| 29 | + } |
25 | 30 |
|
26 |
| -const userB = createUser({ name: "Romain", age: 35, phone: 1234567890 }) |
27 |
| -checkUserB(userB) |
| 31 | + const userB = createUser({ name: "Romain", age: 35, phone: 1234567890 }) |
| 32 | + checkUserB(userB) |
28 | 33 |
|
29 |
| -// @ts-expect-error age should be a number |
30 |
| -const userC = createUser({ name: "Romain", age: "35" }) |
31 |
| -checkUserC(userC) |
| 34 | + // @ts-expect-error age should be a number |
| 35 | + const userC = createUser({ name: "Romain", age: "35" }) |
| 36 | + checkUserC(userC) |
| 37 | + |
| 38 | +} |
32 | 39 |
|
33 |
| -console.log('All tests passed successfully.') |
| 40 | +console.log(`Valibot exec time for ${nbIterations} iterations :`, performance.now() - startTime, 'ms') |
0 commit comments