-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathrouteHandlerBuilder.ts
More file actions
313 lines (282 loc) · 10.4 KB
/
routeHandlerBuilder.ts
File metadata and controls
313 lines (282 loc) · 10.4 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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
// eslint-disable-next-line import/no-named-as-default
import z from 'zod/v4';
import {
HandlerFunction,
HandlerServerErrorFn,
MiddlewareFunction,
MiddlewareResult,
NextFunction,
OriginalRouteHandler,
} from './types';
/**
* Type of the middleware function passed to a safe action client.
*/
export type MiddlewareFn<TContext, TReturnType, TMetadata = unknown> = {
(opts: { context: TContext; request: Request; metadata?: TMetadata }): Promise<TReturnType>;
};
export class InternalRouteHandlerError extends Error {
constructor(message: string) {
super(message);
this.name = 'InternalRouteHandlerError';
}
}
export class RouteHandlerBuilder<
TParams extends z.Schema = z.Schema,
TQuery extends z.Schema = z.Schema,
TBody extends z.Schema = z.Schema,
// eslint-disable-next-line @typescript-eslint/ban-types
TContext = {},
TMetadata extends z.Schema = z.Schema,
> {
readonly config: {
paramsSchema: TParams;
querySchema: TQuery;
bodySchema: TBody;
metadataSchema?: TMetadata;
};
readonly middlewares: Array<MiddlewareFunction<TContext, Record<string, unknown>, z.infer<TMetadata>>>;
readonly handleServerError?: HandlerServerErrorFn;
readonly metadataValue?: z.infer<TMetadata>;
readonly contextType!: TContext;
constructor({
config = {
paramsSchema: undefined as unknown as TParams,
querySchema: undefined as unknown as TQuery,
bodySchema: undefined as unknown as TBody,
metadataSchema: undefined as unknown as TMetadata,
},
middlewares = [],
handleServerError,
contextType,
metadataValue,
}: {
config?: {
paramsSchema: TParams;
querySchema: TQuery;
bodySchema: TBody;
metadataSchema?: TMetadata;
};
middlewares?: Array<MiddlewareFunction<TContext, Record<string, unknown>, z.infer<TMetadata>>>;
handleServerError?: HandlerServerErrorFn;
contextType: TContext;
metadataValue?: z.infer<TMetadata>;
}) {
this.config = config;
this.middlewares = middlewares;
this.handleServerError = handleServerError;
this.contextType = contextType as TContext;
this.metadataValue = metadataValue;
}
/**
* Define the schema for the params
* @param schema - The schema for the params
* @returns A new instance of the RouteHandlerBuilder
*/
params<T extends z.Schema>(schema: T) {
return new RouteHandlerBuilder<T, TQuery, TBody, TContext, TMetadata>({
...this,
config: { ...this.config, paramsSchema: schema },
});
}
/**
* Define the schema for the query
* @param schema - The schema for the query
* @returns A new instance of the RouteHandlerBuilder
*/
query<T extends z.Schema>(schema: T) {
return new RouteHandlerBuilder<TParams, T, TBody, TContext, TMetadata>({
...this,
config: { ...this.config, querySchema: schema },
});
}
/**
* Define the schema for the body
* @param schema - The schema for the body
* @returns A new instance of the RouteHandlerBuilder
*/
body<T extends z.Schema>(schema: T) {
return new RouteHandlerBuilder<TParams, TQuery, T, TContext, TMetadata>({
...this,
config: { ...this.config, bodySchema: schema },
});
}
/**
* Define the schema for the metadata
* @param schema - The schema for the metadata
* @returns A new instance of the RouteHandlerBuilder
*/
defineMetadata<T extends z.Schema>(schema: T) {
return new RouteHandlerBuilder<TParams, TQuery, TBody, TContext, T>({
config: { ...this.config, metadataSchema: schema },
middlewares: [],
handleServerError: this.handleServerError,
contextType: this.contextType,
metadataValue: undefined,
});
}
/**
* Set the metadata value for the route handler
* @param value - The metadata value that will be passed to middlewares
* @returns A new instance of the RouteHandlerBuilder
*/
metadata(value: z.infer<TMetadata>) {
return new RouteHandlerBuilder<TParams, TQuery, TBody, TContext, TMetadata>({
...this,
metadataValue: value,
});
}
/**
* Add a middleware to the route handler
* @param middleware - The middleware function to be executed
* @returns A new instance of the RouteHandlerBuilder
*/
use<TNestContext extends Record<string, unknown>>(
middleware: MiddlewareFunction<TContext, TNestContext & TContext, z.infer<TMetadata>>,
): RouteHandlerBuilder<TParams, TQuery, TBody, TContext & TNestContext, TMetadata> {
type MergedContext = TContext & TNestContext;
return new RouteHandlerBuilder<TParams, TQuery, TBody, MergedContext, TMetadata>({
...this,
middlewares: [...this.middlewares, middleware],
contextType: {} as MergedContext,
});
}
/**
* Create the handler function that will be used by Next.js
* @param handler - The handler function that will be called when the route is hit
* @returns The original route handler that Next.js expects with the validation logic
*/
handler(
handler: HandlerFunction<z.infer<TParams>, z.infer<TQuery>, z.infer<TBody>, TContext, z.infer<TMetadata>>,
): OriginalRouteHandler {
return async (request, context): Promise<Response> => {
try {
const url = new URL(request.url);
let params = context?.params ? await context.params : {};
let query = Object.fromEntries(
[...url.searchParams.keys()].map((key) => {
const values = url.searchParams.getAll(key);
return values.length === 1 ? [key, values[0]] : [key, values];
}),
);
let metadata = this.metadataValue;
// Support both JSON and FormData parsing
let body: unknown = {};
if (request.method !== 'GET' && request.method !== 'DELETE') {
try {
const contentType = request.headers.get('content-type') || '';
if (
contentType.includes('multipart/form-data') ||
contentType.includes('application/x-www-form-urlencoded')
) {
const formData = await request.formData();
body = Object.fromEntries(formData.entries());
} else {
body = await request.json();
}
} catch (error) {
if (this.config.bodySchema) {
throw new InternalRouteHandlerError(JSON.stringify({ message: 'Invalid body', errors: error }));
}
}
}
// Validate the params against the provided schema
if (this.config.paramsSchema) {
const paramsResult = this.config.paramsSchema.safeParse(params);
if (!paramsResult.success) {
throw new InternalRouteHandlerError(
JSON.stringify({ message: 'Invalid params', errors: paramsResult.error.issues }),
);
}
params = paramsResult.data as Record<string, unknown>;
}
// Validate the query against the provided schema
if (this.config.querySchema) {
const queryResult = this.config.querySchema.safeParse(query);
if (!queryResult.success) {
throw new InternalRouteHandlerError(
JSON.stringify({ message: 'Invalid query', errors: queryResult.error.issues }),
);
}
query = queryResult.data;
}
// Validate the body against the provided schema
if (this.config.bodySchema) {
const bodyResult = this.config.bodySchema.safeParse(body);
if (!bodyResult.success) {
throw new InternalRouteHandlerError(
JSON.stringify({ message: 'Invalid body', errors: bodyResult.error.issues }),
);
}
body = bodyResult.data;
}
// Validate the metadata against the provided schema
if (this.config.metadataSchema && metadata !== undefined) {
const metadataResult = this.config.metadataSchema.safeParse(metadata);
if (!metadataResult.success) {
throw new InternalRouteHandlerError(
JSON.stringify({ message: 'Invalid metadata', errors: metadataResult.error.issues }),
);
}
metadata = metadataResult.data;
}
// Execute middleware chain
let middlewareContext: TContext = {} as TContext;
const executeMiddlewareChain = async (index: number): Promise<Response> => {
if (index >= this.middlewares.length) {
try {
const result = await handler(request, {
params: params as z.infer<TParams>,
query: query as z.infer<TQuery>,
body: body as z.infer<TBody>,
ctx: middlewareContext,
metadata: metadata as z.infer<TMetadata>,
});
if (result instanceof Response) return result;
return new Response(JSON.stringify(result), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
return handleError(error as Error, this.handleServerError);
}
}
const middleware = this.middlewares[index];
if (!middleware) return executeMiddlewareChain(index + 1);
const next: NextFunction<TContext> = async (options = {}) => {
if (options.ctx) {
middlewareContext = { ...middlewareContext, ...options.ctx };
}
const result = await executeMiddlewareChain(index + 1);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return result as MiddlewareResult<any>;
};
try {
const result = await middleware({
request,
ctx: middlewareContext,
metadata,
next,
});
if (result instanceof Response) return result;
middlewareContext = { ...middlewareContext };
return result;
} catch (error) {
return handleError(error as Error, this.handleServerError);
}
};
return executeMiddlewareChain(0);
} catch (error) {
return handleError(error as Error, this.handleServerError);
}
};
}
}
const handleError = (error: Error, handleServerError?: HandlerServerErrorFn): Response => {
if (error instanceof InternalRouteHandlerError) {
return new Response(error.message, { status: 400 });
}
if (handleServerError) {
return handleServerError(error as Error);
}
return new Response(JSON.stringify({ message: 'Internal server error' }), { status: 500 });
};