Skip to content

Commit

Permalink
Fix serialization logic
Browse files Browse the repository at this point in the history
  • Loading branch information
samchungy committed Jan 24, 2025
1 parent df8ae4f commit 31c848c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/serializerCompiler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,31 @@ describe('serializerCompiler', () => {
expect(result.json()).toEqual({ jobId: '60002023' });
});

it('should handle a route without a schema', async () => {
const app = fastify();

app.setSerializerCompiler(serializerCompiler);
app.post(
'/',
{
schema: {
response: {
200: {},
},
},
},
async (_req, res) =>
res.send({
jobId: '60002023',
}),
);
await app.ready();

const result = await app.inject().post('/');

expect(result.json()).toEqual({ jobId: '60002023' });
});

it('should fail an invalid response', async () => {
const app = fastify();

Expand Down
5 changes: 5 additions & 0 deletions src/serializerCompiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { FastifySerializerCompiler } from 'fastify/types/schema';
import type { ZodType, ZodTypeAny } from 'zod';
import { createSchema } from 'zod-openapi';

import { isZodType } from './transformer';
import { ResponseSerializationError } from './validationError';

export interface SerializerOptions {
Expand All @@ -16,6 +17,10 @@ export interface SerializerOptions {
export const createSerializerCompiler =
(opts?: SerializerOptions): FastifySerializerCompiler<ZodType> =>
({ schema, method, url }) => {
if (!isZodType(schema)) {
return opts?.stringify ?? JSON.stringify;
}

let stringify = opts?.stringify;
if (!stringify) {
const { schema: jsonSchema, components } = createSchema(schema, {
Expand Down

0 comments on commit 31c848c

Please sign in to comment.