Skip to content

Commit 4444929

Browse files
fix(ts-rest-fastify): fix request body validation (#329)
* fix(ts-rest-fastify): fix request body validation * Add changeset * Update light-hotels-think.md --------- Co-authored-by: Michael Angelo Rivera <55844504+michaelangelo-io@users.noreply.github.com>
1 parent f14ad97 commit 4444929

3 files changed

Lines changed: 42 additions & 1 deletion

File tree

.changeset/light-hotels-think.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@ts-rest/fastify': patch
3+
---
4+
5+
Pass the parsed request body from zod to the route handler instead of the original request.

libs/ts-rest/fastify/src/lib/ts-rest-fastify.spec.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,42 @@ describe('ts-rest-fastify', () => {
220220
expect(response.body).toEqual({ id: 'foo' });
221221
});
222222

223+
it('should remove extra properties from request body', async () => {
224+
const contract = c.router({
225+
echo: {
226+
method: 'POST',
227+
path: '/echo',
228+
body: z.object({
229+
foo: z.string(),
230+
}),
231+
responses: {
232+
200: z.any(),
233+
},
234+
},
235+
});
236+
237+
const router = s.router(contract, {
238+
echo: async ({ body }) => {
239+
return {
240+
status: 200,
241+
body: body,
242+
};
243+
},
244+
});
245+
246+
const app = fastify({ logger: false });
247+
248+
s.registerRouter(contract, router, app);
249+
250+
await app.ready();
251+
252+
const response = await supertest(app.server).post('/echo').send({
253+
foo: 'bar',
254+
bar: 'foo',
255+
});
256+
expect(response.body).toEqual({ foo: 'bar' });
257+
});
258+
223259
it('options.responseValidation true should remove extra properties', async () => {
224260
const app = fastify({ logger: false });
225261

libs/ts-rest/fastify/src/lib/ts-rest-fastify.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ const registerRoute = <TAppRoute extends AppRoute>(
218218
headers: validationResults.headersResult.data as any,
219219
request,
220220
// eslint-disable-next-line @typescript-eslint/no-explicit-any
221-
body: request.body as any,
221+
body: validationResults.bodyResult.data as any,
222222
reply,
223223
});
224224

0 commit comments

Comments
 (0)