Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import type {
RawServerBase,
RawServerDefault,
} from 'fastify'
import type { $ZodRegistry, input, output } from 'zod/v4/core'
import { $ZodType, globalRegistry, safeParse } from 'zod/v4/core'
import type { $ZodRegistry, output } from 'zod/v4/core'
import { $ZodType, globalRegistry, safeEncode, safeParse } from 'zod/v4/core'
import { createValidationError, InvalidSchemaError, ResponseSerializationError } from './errors'
import { getOASVersion, jsonSchemaToOAS } from './json-to-oas'
import { type ZodToJsonConfig, zodRegistryToJson, zodSchemaToJson } from './zod-to-json'
Expand All @@ -30,7 +30,7 @@ const defaultSkipList = [

export interface ZodTypeProvider extends FastifyTypeProvider {
validator: this['schema'] extends $ZodType ? output<this['schema']> : unknown
serializer: this['schema'] extends $ZodType ? input<this['schema']> : unknown
serializer: this['schema'] extends $ZodType ? output<this['schema']> : unknown
}

interface Schema extends FastifySchema {
Expand Down Expand Up @@ -215,7 +215,7 @@ export const createSerializerCompiler =
(data) => {
const schema = resolveSchema(maybeSchema)

const result = safeParse(schema, data)
const result = safeEncode(schema, data)
if (result.error) {
throw new ResponseSerializationError(method, url, {
cause: result.error,
Expand Down
70 changes: 70 additions & 0 deletions test/response-schema.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,76 @@ describe('response schema', () => {
})
})

describe('correctly processes response schema (codec)', () => {
let app: FastifyInstance
beforeEach(async () => {
const REPLY_SCHEMA = z.object({
value: z.codec(z.string().regex(z.regexes.integer), z.int(), {
decode: (str) => Number.parseInt(str, 10),
encode: (num) => num.toString(),
}),
})

app = Fastify()
app.setValidatorCompiler(validatorCompiler)
app.setSerializerCompiler(serializerCompiler)

app.after(() => {
app.withTypeProvider<ZodTypeProvider>().route({
method: 'GET',
url: '/',
schema: {
response: {
200: REPLY_SCHEMA,
},
},
handler: (_req, res) => {
res.send({ value: 1234 })
},
})

app.withTypeProvider<ZodTypeProvider>().route({
method: 'GET',
url: '/incorrect',
schema: {
response: {
200: REPLY_SCHEMA,
},
},
handler: (_req, res) => {
res.send({ value: '1234' as any })
},
})
})

await app.ready()
})
afterAll(async () => {
await app.close()
})

it('returns 200 for correct response', async () => {
const response = await app.inject().get('/')

expect(response.statusCode).toBe(200)
expect(response.json()).toEqual({ value: '1234' })
})

it('returns 500 for incorrect response', async () => {
const response = await app.inject().get('/incorrect')

expect(response.statusCode).toBe(500)
expect(response.json()).toMatchInlineSnapshot(`
{
"code": "FST_ERR_RESPONSE_SERIALIZATION",
"error": "Internal Server Error",
"message": "Response doesn't match the schema",
"statusCode": 500,
}
`)
})
})

describe('correctly replaces date in stringified response', () => {
let app: FastifyInstance
beforeAll(async () => {
Expand Down