Repository navigation
Expand file tree
/
Copy pathtest.ts
More file actions
67 lines (62 loc) · 1.9 KB
/
Copy pathtest.ts
File metadata and controls
67 lines (62 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import z, {type ZodTypeAny} from 'zod';
import {App, type TriFrostRouter} from './lib/';
import {type TFValidator, type TFInput} from './lib/types/validation';
import {type TriFrostContext} from './lib/types/context';
/**
* Wrap Zod schemas into a TFValidator.
*/
export function zValidator<
TBody extends ZodTypeAny | undefined,
TQuery extends ZodTypeAny | undefined,
Env extends Record<string, any> = {},
State extends Record<string, unknown> = {},
>(
schemas: {body?: TBody; query?: TQuery},
onInvalid?: (ctx: TriFrostContext<Env, State>, err: unknown) => void | Promise<void>,
): TFValidator<
TFInput<TBody extends ZodTypeAny ? z.infer<TBody> : {}, TQuery extends ZodTypeAny ? z.infer<TQuery> & Record<string, unknown> : {}>,
Env,
State
> {
type TInput = TFInput<
TBody extends ZodTypeAny ? z.infer<TBody> : {},
TQuery extends ZodTypeAny ? z.infer<TQuery> & Record<string, unknown> : {}
>;
return {
parse: raw =>
({
body: schemas.body ? schemas.body.parse(raw.body) : ({} as any),
query: schemas.query ? schemas.query.parse(raw.query) : ({} as any),
}) as TInput,
onInvalid,
} satisfies TFValidator<TInput, Env, State>;
}
/**
* Example schemas
*/
const UserSchema = {
body: z.object({name: z.string(), age: z.number()}),
query: z.object({active: z.boolean().optional()}),
};
/**
* Router with routes
*/
export function groupsRouter(r: TriFrostRouter) {
return r
.get('/submit', ctx => {
return ctx.json({hello: 'world'});
})
.post('/submitForm', {
input: zValidator(UserSchema),
fn: ctx => {
return ctx.json({
user: ctx.body.age,
filter: ctx.query,
});
},
});
}
/**
* Mount onto app
*/
new App().group('', groupsRouter);