From 789b06cc1b24c911c5b4c8e7ab1223c9128bab7c Mon Sep 17 00:00:00 2001 From: giancarlo Date: Wed, 29 May 2024 13:28:16 +0700 Subject: [PATCH] Update route handler to include route parameters The changes include updating the route handler function to receive an additional argument containing the route parameters. The body type in the request parameters was also updated to define it as undefined instead of never when --- packages/next/src/routes/index.ts | 35 ++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/packages/next/src/routes/index.ts b/packages/next/src/routes/index.ts index 9f07ab0d5..7984e4449 100644 --- a/packages/next/src/routes/index.ts +++ b/packages/next/src/routes/index.ts @@ -27,7 +27,8 @@ interface HandlerParams< > { request: NextRequest; user: RequireAuth extends false ? undefined : User; - body: Schema extends z.ZodType ? z.infer : never; + body: Schema extends z.ZodType ? z.infer : undefined; + params: Record; } /** @@ -70,7 +71,12 @@ export const enhanceRouteHandler = < * * This function takes a request object as an argument and returns a response object. */ - return async function routeHandler(request: NextRequest) { + return async function routeHandler( + request: NextRequest, + routeParams: { + params: Record; + }, + ) { type UserParam = Params['auth'] extends false ? undefined : User; let user: UserParam = undefined as UserParam; @@ -107,19 +113,27 @@ export const enhanceRouteHandler = < user = auth.data as UserParam; } - // clone the request to read the body - // so that we can pass it to the handler safely - let body = await request.clone().json(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let body: any; if (params?.schema) { - body = zodParseFactory(params.schema)(body); + // clone the request to read the body + // so that we can pass it to the handler safely + const json = await request.clone().json(); + + body = zodParseFactory(params.schema)(json); } const shouldCaptureException = params?.captureException ?? true; if (shouldCaptureException) { try { - return await handler({ request, body, user }); + return await handler({ + request, + body, + user, + params: routeParams.params, + }); } catch (error) { if (isRedirectError(error)) { throw error; @@ -132,7 +146,12 @@ export const enhanceRouteHandler = < } } else { // all good, call the handler with the request, body and user - return handler({ request, body, user }); + return handler({ + request, + body, + user, + params: routeParams.params, + }); } }; };