-
Notifications
You must be signed in to change notification settings - Fork 357
Expand file tree
/
Copy pathroute.ts
More file actions
184 lines (166 loc) · 5.41 KB
/
Copy pathroute.ts
File metadata and controls
184 lines (166 loc) · 5.41 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import type { H3RouteMeta, HTTPMethod } from "../types/h3.ts";
import type { EventHandlerRequest, Middleware } from "../types/handler.ts";
import type { H3Plugin, H3 } from "../types/h3.ts";
import type { H3Event } from "../event.ts";
import type { StandardSchemaV1, InferOutput } from "./internal/standard-schema.ts";
import type { OnValidateError } from "./internal/validate.ts";
import { defineValidatedHandler } from "../handler.ts";
type StringHeaders<T> = {
[K in keyof T]: Extract<T[K], string>;
};
/**
* Route validation schemas
*/
export interface RouteValidation {
body?: StandardSchemaV1;
headers?: StandardSchemaV1;
query?: StandardSchemaV1;
params?: StandardSchemaV1;
response?: StandardSchemaV1;
onError?: OnValidateError;
}
type RouteValidationConfig<V extends RouteValidation> = Omit<V, "onError"> & {
onError?: OnValidateError;
};
type RouteEventRequest<V extends RouteValidation> = EventHandlerRequest & {
body: NonNullable<V["body"]> extends StandardSchemaV1
? InferOutput<NonNullable<V["body"]>>
: unknown;
query: NonNullable<V["query"]> extends StandardSchemaV1
? StringHeaders<InferOutput<NonNullable<V["query"]>>>
: Partial<Record<string, string>>;
routerParams: NonNullable<V["params"]> extends StandardSchemaV1
? InferOutput<NonNullable<V["params"]>>
: Record<string, string>;
};
type RouteEventParams<V extends RouteValidation> =
NonNullable<V["params"]> extends StandardSchemaV1
? InferOutput<NonNullable<V["params"]>>
: Record<string, string>;
type RouteResponse<V extends RouteValidation> =
NonNullable<V["response"]> extends StandardSchemaV1
? InferOutput<NonNullable<V["response"]>>
: unknown;
/**
* Route definition options with type-safe validation
*/
export interface RouteDefinition<V extends RouteValidation = RouteValidation> {
/**
* HTTP method for the route, e.g. 'GET', 'POST', etc.
*/
method: HTTPMethod;
/**
* Route pattern, e.g. '/api/users/:id'
*/
route: string;
/**
* Handler function for the route.
*/
handler: (
event: ValidatedRouteEvent<RouteEventRequest<V>, RouteEventParams<V>>,
) => RouteResponse<V> | Promise<RouteResponse<V>>;
/**
* Optional middleware to run before the handler.
*/
middleware?: Middleware[];
/**
* Additional route metadata.
*/
meta?: H3RouteMeta;
/**
* Validation schemas for request and response
*/
validate?: RouteValidationConfig<V>;
}
// Helper type for validated H3Event with typed context.params
type ValidatedRouteEvent<RequestT extends EventHandlerRequest, ParamsT> = Omit<
H3Event<RequestT>,
"context"
> & {
context: Omit<H3Event["context"], "params"> & {
params?: ParamsT;
};
};
// Overload: With validation
export function defineRoute<
Body extends StandardSchemaV1 = never,
Headers extends StandardSchemaV1 = never,
Query extends StandardSchemaV1 = never,
Params extends StandardSchemaV1 = never,
Response extends StandardSchemaV1 = never,
>(def: {
method: HTTPMethod;
route: string;
validate: {
body?: Body;
headers?: Headers;
query?: Query;
params?: Params;
response?: Response;
onError?: OnValidateError;
};
handler: (
event: ValidatedRouteEvent<
EventHandlerRequest & {
body: [Body] extends [never] ? unknown : InferOutput<Body>;
query: [Query] extends [never]
? Partial<Record<string, string>>
: StringHeaders<InferOutput<Query>>;
routerParams: [Params] extends [never] ? Record<string, string> : InferOutput<Params>;
},
[Params] extends [never] ? Record<string, string> : InferOutput<Params>
>,
) =>
| ([Response] extends [never] ? unknown : InferOutput<Response>)
| Promise<[Response] extends [never] ? unknown : InferOutput<Response>>;
middleware?: Middleware[];
meta?: H3RouteMeta;
}): H3Plugin;
// Overload: Without validation
export function defineRoute(def: {
method: HTTPMethod;
route: string;
handler: (event: H3Event) => unknown | Promise<unknown>;
middleware?: Middleware[];
meta?: H3RouteMeta;
validate?: never;
}): H3Plugin;
/**
* Define a route as a plugin that can be registered with app.register()
*
* Routes defined with this function automatically get type-safe validation
* for params, query, body, and response based on the provided schemas.
*
* @example
* ```js
* import { z } from "zod";
*
* const userRoute = defineRoute({
* method: 'POST',
* route: '/api/users/:id',
* validate: {
* params: z.object({ id: z.string().uuid() }),
* query: z.object({ include: z.string().optional() }),
* body: z.object({ name: z.string() }),
* response: z.object({ id: z.string(), name: z.string() }),
* },
* handler: (event) => {
* // event.context.params, await event.req.json(), and return value are all typed!
* const { id } = event.context.params;
* const body = await event.req.json();
* return { id, name: body.name };
* }
* });
*
* app.use(userRoute);
* ```
*/
export function defineRoute<V extends RouteValidation>(def: RouteDefinition<V>): H3Plugin {
// TypeScript cannot infer complex conditional types between RouteDefinition and
// defineValidatedHandler parameters. Runtime types are identical and safe.
type ValidatedHandlerParam = Parameters<typeof defineValidatedHandler>[0];
const handler = defineValidatedHandler(def as unknown as ValidatedHandlerParam);
return (h3: H3) => {
h3.on(def.method, def.route, handler);
};
}