Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 1 addition & 4 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,4 @@ export {
validatorCompiler,
} from './src/core';

export {
ResponseValidationError,
type ResponseValidationErrorDetails,
} from './src/ResponseValidationError';
export { ResponseValidationError, InvalidSchemaError } from './src/errors';
25 changes: 0 additions & 25 deletions src/ResponseValidationError.ts

This file was deleted.

41 changes: 18 additions & 23 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import type { FastifySerializerCompiler } from 'fastify/types/schema';
import type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';
import type { z } from 'zod';

import { ResponseValidationError } from './ResponseValidationError';
import { createValidationError, InvalidSchemaError, ResponseValidationError } from './errors';
import { resolveRefs } from './ref';
import { convertZodToJsonSchema } from './zod-to-json';

Expand Down Expand Up @@ -108,44 +108,39 @@ export const createJsonSchemaTransformObject =
};

export const validatorCompiler: FastifySchemaCompiler<z.ZodTypeAny> =
({ schema }) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(data): any => {
try {
return { value: schema.parse(data) };
} catch (error) {
return { error };
({ schema, method, url }) =>
(data) => {
const result = schema.safeParse(data);
if (result.error) {
return { error: createValidationError(result.error, method, url) as unknown as Error };
}
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function hasOwnProperty<T, K extends PropertyKey>(obj: T, prop: K): obj is T & Record<K, any> {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
return { value: result.data };
};

function resolveSchema(maybeSchema: z.ZodTypeAny | { properties: z.ZodTypeAny }): z.ZodTypeAny {
if (hasOwnProperty(maybeSchema, 'safeParse')) {
return maybeSchema as z.ZodTypeAny;
const resolveSchema = (maybeSchema: z.ZodTypeAny | { properties: z.ZodTypeAny }) => {
if ('safeParse' in maybeSchema) {
return maybeSchema;
}
if (hasOwnProperty(maybeSchema, 'properties')) {
if ('properties' in maybeSchema) {
return maybeSchema.properties;
}
throw new Error(`Invalid schema passed: ${JSON.stringify(maybeSchema)}`);
}
throw new InvalidSchemaError(JSON.stringify(maybeSchema));
};

export const serializerCompiler: FastifySerializerCompiler<
z.ZodTypeAny | { properties: z.ZodTypeAny }
> =
({ schema: maybeSchema, method, url }) =>
({ schema: maybeSchema }) =>
(data) => {
const schema = resolveSchema(maybeSchema);

const result = schema.safeParse(data);
if (result.success) {
return JSON.stringify(result.data);
if (result.error) {
throw new ResponseValidationError({ cause: result.error });
}

throw new ResponseValidationError(result, method, url);
return JSON.stringify(result.data);
};

/**
Expand Down
33 changes: 33 additions & 0 deletions src/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import createError from '@fastify/error';
import type { FastifySchemaValidationError } from 'fastify/types/schema';
import type { ZodError } from 'zod';

export const ResponseValidationError = createError<[{ cause: Error }]>(
'FST_ERR_RESPONSE_VALIDATION',
"Response doesn't match the schema",
500,
);

export const InvalidSchemaError = createError<[string]>(
'FST_ERR_INVALID_SCHEMA',
'Invalid schema passed: %s',
500,
);

export const createValidationError = (
error: ZodError,
method: string,
url: string,
): FastifySchemaValidationError[] =>
error.errors.map((issue) => ({
keyword: issue.code,
instancePath: `/${issue.path.join('/')}`,
schemaPath: `#/${issue.path.join('/')}/${issue.code}`,
params: {
issue,
zodError: error,
method,
url,
},
message: error.message,
}));
2 changes: 1 addition & 1 deletion test/request-schema.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ describe('response schema', () => {
{
"code": "FST_ERR_VALIDATION",
"error": "Bad Request",
"message": "[
"message": "querystring/name [
{
"code": "invalid_type",
"expected": "string",
Expand Down
17 changes: 1 addition & 16 deletions test/response-schema.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import type { FastifyInstance } from 'fastify';
import Fastify from 'fastify';
import { z } from 'zod';

import type { ResponseValidationError } from '../src/ResponseValidationError';
import type { ZodTypeProvider } from '../src/core';
import { serializerCompiler, validatorCompiler } from '../src/core';

Expand Down Expand Up @@ -47,7 +46,6 @@ describe('response schema', () => {
return reply.code(500).send({
error: 'Internal Server Error',
message: "Response doesn't match the schema",
details: (err as unknown as ResponseValidationError).details,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why can't we return details here and assert that validation error exposes enough details?

Copy link
Contributor Author

@Bram-dc Bram-dc Sep 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no details on ResponseSerializationError.

We would now have to access it through error.cause.

edited since I stated it wrong

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that's fine, can we use that field to preserve the initial test logic?

Copy link
Contributor Author

@Bram-dc Bram-dc Sep 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, I also made a mistake so I renamed ResponseValidationError to ResponseSerializationError since that is what it is.

Copy link
Contributor Author

@Bram-dc Bram-dc Sep 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Validation errors can be accessed through error.validation as described in the docs.

https://fastify.dev/docs/latest/Reference/Validation-and-Serialization/#error-handling

fastify.setErrorHandler(function (error, request, reply) {
  if (error.validation) {
     reply.status(422).send(new Error('validation failed'))
  }
})

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fastify error model really isn't very flexible :-/
trying to augment errors we are getting there currently

statusCode: 500,
});
});
Expand All @@ -71,19 +69,6 @@ describe('response schema', () => {
expect(response.statusCode).toBe(500);
expect(response.json()).toMatchInlineSnapshot(`
{
"details": {
"error": [
{
"code": "invalid_type",
"expected": "undefined",
"message": "Expected undefined, received object",
"path": [],
"received": "object",
},
],
"method": "GET",
"url": "/incorrect",
},
"error": "Internal Server Error",
"message": "Response doesn't match the schema",
"statusCode": 500,
Expand Down Expand Up @@ -149,7 +134,7 @@ describe('response schema', () => {

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