Skip to content

Commit 4e166b3

Browse files
authored
fix(fastify): crashing on malformed request json (#548)
1 parent 942da50 commit 4e166b3

3 files changed

Lines changed: 54 additions & 1 deletion

File tree

.changeset/proud-dots-smile.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+
Fix fastify crashing on malformed request JSON

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

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -485,7 +485,55 @@ describe('ts-rest-fastify', () => {
485485
.get('/test')
486486
.timeout(1000)
487487
.send({});
488+
488489
expect(response.statusCode).toEqual(500);
490+
expect(response.body).toEqual({
491+
error: 'Internal Server Error',
492+
message: 'not implemented',
493+
statusCode: 500,
494+
});
495+
});
496+
497+
it('should handle JSON parsing error', async () => {
498+
const erroringContract = c.router({
499+
ping: {
500+
method: 'POST',
501+
path: '/ping',
502+
body: z.object({
503+
ping: z.string(),
504+
}),
505+
responses: {
506+
200: z.object({
507+
pong: z.string(),
508+
}),
509+
},
510+
},
511+
});
512+
513+
const erroringRouter = s.router(erroringContract, {
514+
ping: async () => {
515+
throw new Error('not implemented');
516+
},
517+
});
518+
519+
const app = fastify({ logger: false });
520+
521+
s.registerRouter(erroringContract, erroringRouter, app);
522+
523+
await app.ready();
524+
525+
const response = await supertest(app.server)
526+
.post('/ping')
527+
.timeout(1000)
528+
.set('Content-Type', 'application/json')
529+
.send('{');
530+
531+
expect(response.statusCode).toEqual(400);
532+
expect(response.body).toEqual({
533+
error: 'Bad Request',
534+
message: 'Unexpected end of JSON input',
535+
statusCode: 400,
536+
});
489537
});
490538

491539
it('should be able to instantiate two routers and combine them together', async () => {

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ const requestValidationErrorHandler = (
182182
return handler(err, request, reply);
183183
}
184184
} else {
185-
throw err;
185+
return reply.send(err);
186186
}
187187
};
188188
};

0 commit comments

Comments
 (0)