From 5bdd3b2aa4fd8c3c2cfa36496e7d0f8e3bfcb5f1 Mon Sep 17 00:00:00 2001 From: David Crespo Date: Fri, 1 Dec 2023 20:35:32 -0600 Subject: [PATCH] fix error response bug due to Response inside another Response --- client/msw-handlers.ts | 18 +++++++----------- generator/client/msw-handlers.ts | 18 +++++++----------- 2 files changed, 14 insertions(+), 22 deletions(-) diff --git a/client/msw-handlers.ts b/client/msw-handlers.ts index f380fa0..be337b7 100644 --- a/client/msw-handlers.ts +++ b/client/msw-handlers.ts @@ -1025,13 +1025,6 @@ export interface MSWHandlers { }) => Promisable; } -function validateBody(schema: S, body: unknown) { - const result = schema.transform(snakeify).safeParse(body); - if (result.success) { - return { body: result.data as Json> }; - } - return { bodyErr: json(result.error.issues, { status: 400 }) }; -} function validateParams( schema: S, req: Request, @@ -1083,10 +1076,13 @@ const handler = const { path, query } = params; - const { body, bodyErr } = bodySchema - ? validateBody(bodySchema, await req.json()) - : { body: undefined, bodyErr: undefined }; - if (bodyErr) return json(bodyErr, { status: 400 }); + let body = undefined; + if (bodySchema) { + const rawBody = await req.json(); + const result = bodySchema.transform(snakeify).safeParse(body); + if (!result.success) return json(result.error.issues, { status: 400 }); + body = result.data; + } try { // TypeScript can't narrow the handler down because there's not an explicit relationship between the schema diff --git a/generator/client/msw-handlers.ts b/generator/client/msw-handlers.ts index db1db45..4822724 100644 --- a/generator/client/msw-handlers.ts +++ b/generator/client/msw-handlers.ts @@ -119,13 +119,6 @@ export function generateMSWHandlers(spec: OpenAPIV3.Document) { w("}"); w(` - function validateBody(schema: S, body: unknown) { - const result = schema.transform(snakeify).safeParse(body); - if (result.success) { - return { body: result.data as Json> } - } - return { bodyErr: json(result.error.issues, { status: 400 }) } - } function validateParams(schema: S, req: Request, pathParams: PathParams) { const rawParams = new URLSearchParams(new URL(req.url).search) const params: [string, unknown][] = [] @@ -168,10 +161,13 @@ export function generateMSWHandlers(spec: OpenAPIV3.Document) { const { path, query } = params - const { body, bodyErr } = bodySchema - ? validateBody(bodySchema, await req.json()) - : { body: undefined, bodyErr: undefined }; - if (bodyErr) return json(bodyErr, { status: 400 }); + let body = undefined + if (bodySchema) { + const rawBody = await req.json() + const result = bodySchema.transform(snakeify).safeParse(body); + if (!result.success) return json(result.error.issues, { status: 400 }) + body = result.data + } try { // TypeScript can't narrow the handler down because there's not an explicit relationship between the schema