Skip to content

Commit 56a9929

Browse files
committed
add path params validator
1 parent ba29000 commit 56a9929

File tree

2 files changed

+11
-7
lines changed

2 files changed

+11
-7
lines changed

src/core/path-params.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import type { ZodType } from "zod";
2+
3+
export default function parsePathParams<T>(source: unknown, schema?: ZodType<T>) {
4+
if (!schema) return null;
5+
return schema.parse(source);
6+
}

src/index.ts

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { type ZodType } from "zod";
22
import { parseRequestBody, resolveRequestBody } from "./core/body";
33
import { resolveParams } from "./core/params";
4+
import parsePathParams from "./core/path-params";
45
import { addBadRequest, bundleResponses } from "./core/responses";
56
import parseSearchParams from "./core/search-params";
67
import type { HttpMethod } from "./types/http";
@@ -39,13 +40,10 @@ export default function createRoute<M extends HttpMethod, PP, QP, RB>(input: Rou
3940
const handler: RouteMethodHandler<PP> = async (request, props) => {
4041
try {
4142
const { searchParams } = new URL(request.url);
42-
const queryParams = parseSearchParams(searchParams, input.queryParams);
43-
const body = await parseRequestBody(request, input.method, input.requestBody ?? undefined);
44-
return await input.action({
45-
pathParams: (props.params ?? null) as PP,
46-
queryParams: queryParams as QP,
47-
body: body as RB,
48-
});
43+
const pathParams = parsePathParams(props.params, input.pathParams) as PP;
44+
const queryParams = parseSearchParams(searchParams, input.queryParams) as QP;
45+
const body = await parseRequestBody(request, input.method, input.requestBody ?? undefined) as RB;
46+
return await input.action({ pathParams, queryParams, body });
4947
} catch (error) {
5048
if (error instanceof Error && error.constructor.name === "ZodError") {
5149
return new Response(null, { status: 400 });

0 commit comments

Comments
 (0)