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
This commit is contained in:
giancarlo
2024-05-29 13:28:16 +07:00
parent 7f4bfb15e5
commit 789b06cc1b

View File

@@ -27,7 +27,8 @@ interface HandlerParams<
> {
request: NextRequest;
user: RequireAuth extends false ? undefined : User;
body: Schema extends z.ZodType ? z.infer<Schema> : never;
body: Schema extends z.ZodType ? z.infer<Schema> : undefined;
params: Record<string, string>;
}
/**
@@ -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<string, string>;
},
) {
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,
});
}
};
};