Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Provide correct error message on the validation error. #115

Merged
merged 7 commits into from
Sep 28, 2024
Merged
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
7 changes: 6 additions & 1 deletion index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,9 @@ export {
createSerializerCompiler,
} from './src/core';

export { ResponseSerializationError, InvalidSchemaError } from './src/errors';
export {
type ZodFastifySchemaValidationError,
ResponseSerializationError,
InvalidSchemaError,
hasZodFastifySchemaValidationErrors,
} from './src/errors';
6 changes: 3 additions & 3 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,11 @@ export const createJsonSchemaTransformObject =
};

export const validatorCompiler: FastifySchemaCompiler<z.ZodTypeAny> =
({ schema, method, url }) =>
({ schema }) =>
(data) => {
const result = schema.safeParse(data);
if (result.error) {
return { error: createValidationError(result.error, method, url) as unknown as Error };
return { error: createValidationError(result.error) as unknown as Error };
}

return { value: result.data };
Expand Down Expand Up @@ -146,7 +146,7 @@ export const createSerializerCompiler =

const result = schema.safeParse(data);
if (result.error) {
throw new ResponseSerializationError(result.error, method, url);
throw new ResponseSerializationError(method, url, { cause: result.error });
}

return JSON.stringify(result.data, options?.replacer);
Expand Down
49 changes: 37 additions & 12 deletions src/errors.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import createError from '@fastify/error';
import type { FastifySchemaValidationError } from 'fastify/types/schema';
import type { ZodError } from 'zod';
import type { FastifyError } from 'fastify';
import type { ZodError, ZodIssue, ZodIssueCode } from 'zod';

export class ResponseSerializationError extends createError<[{ cause: ZodError }]>(
'FST_ERR_RESPONSE_SERIALIZATION',
"Response doesn't match the schema",
500,
) {
constructor(
public cause: ZodError,
public method: string,
public url: string,
options: { cause: ZodError },
) {
super({ cause });
super({ cause: options.cause });
}
}

Expand All @@ -22,20 +22,45 @@ export const InvalidSchemaError = createError<[string]>(
500,
);

export const createValidationError = (
error: ZodError,
method: string,
url: string,
): FastifySchemaValidationError[] =>
export type ZodFastifySchemaValidationError = {
name: 'ZodFastifySchemaValidationError';
keyword: ZodIssueCode;
instancePath: string;
schemaPath: string;
params: {
issue: ZodIssue;
zodError: ZodError;
};
message: string;
};

const isZodFastifySchemaValidationError = (
error: unknown,
): error is ZodFastifySchemaValidationError =>
typeof error === 'object' &&
error !== null &&
'name' in error &&
error.name === 'ZodFastifySchemaValidationError';

export const hasZodFastifySchemaValidationErrors = (
error: unknown,
): error is FastifyError & { validation: ZodFastifySchemaValidationError[] } =>
typeof error === 'object' &&
error !== null &&
'validation' in error &&
Array.isArray(error.validation) &&
error.validation.length > 0 &&
isZodFastifySchemaValidationError(error.validation[0]);

export const createValidationError = (error: ZodError): ZodFastifySchemaValidationError[] =>
error.errors.map((issue) => ({
name: 'ZodFastifySchemaValidationError',
keyword: issue.code,
instancePath: `/${issue.path.join('/')}`,
schemaPath: `#/${issue.path.join('/')}/${issue.code}`,
params: {
issue,
zodError: error,
method,
url,
},
message: error.message,
message: issue.message,
}));
132 changes: 132 additions & 0 deletions test/request-schema-error-handler.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import type { FastifyInstance } from 'fastify';
import Fastify from 'fastify';
import { z } from 'zod';

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

describe('response schema with custom error handler', () => {
let app: FastifyInstance;
beforeAll(async () => {
const REQUEST_SCHEMA = z.object({
name: z.string(),
});

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

app.after(() => {
app
.withTypeProvider<ZodTypeProvider>()
.route({
method: 'POST',
url: '/',
schema: {
body: REQUEST_SCHEMA,
},
handler: (req, res) => {
res.send({
name: req.body.name,
});
},
})
.route({
method: 'GET',
url: '/',
schema: {
querystring: REQUEST_SCHEMA,
},
handler: (req, res) => {
res.send({
name: req.query.name,
});
},
})
.route({
method: 'GET',
url: '/no-schema',
schema: undefined,
handler: (req, res) => {
res.send({
status: 'ok',
});
},
});
});
app.setErrorHandler((err, req, reply) => {
if (hasZodFastifySchemaValidationErrors(err)) {
return reply.code(400).send({
error: 'Response Validation Error',
message: "Request doesn't match the schema",
statusCode: 400,
details: {
issues: err.validation,
method: req.method,
url: req.url,
},
});
}
throw err;
});

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

it('returns 400 and custom error on body validation error', async () => {
const response = await app.inject().post('/').body({
surname: 'dummy',
});

expect(response.statusCode).toBe(400);
expect(response.json()).toMatchInlineSnapshot(`
{
"details": {
"issues": [
{
"instancePath": "/name",
"keyword": "invalid_type",
"message": "Required",
"name": "ZodFastifySchemaValidationError",
"params": {
"issue": {
"code": "invalid_type",
"expected": "string",
"message": "Required",
"path": [
"name",
],
"received": "undefined",
},
"zodError": {
"issues": [
{
"code": "invalid_type",
"expected": "string",
"message": "Required",
"path": [
"name",
],
"received": "undefined",
},
],
"name": "ZodError",
},
},
"schemaPath": "#/name/invalid_type",
},
],
"method": "POST",
"url": "/",
},
"error": "Response Validation Error",
"message": "Request doesn't match the schema",
"statusCode": 400,
}
`);
});
});
34 changes: 3 additions & 31 deletions test/request-schema.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,17 +89,7 @@ describe('response schema', () => {
{
"code": "FST_ERR_VALIDATION",
"error": "Bad Request",
"message": "querystring/name [
{
"code": "invalid_type",
"expected": "string",
"received": "undefined",
"path": [
"name"
],
"message": "Required"
}
]",
"message": "querystring/name Required",
"statusCode": 400,
}
`);
Expand All @@ -115,17 +105,7 @@ describe('response schema', () => {
{
"code": "FST_ERR_VALIDATION",
"error": "Bad Request",
"message": "body/name [
{
"code": "invalid_type",
"expected": "string",
"received": "undefined",
"path": [
"name"
],
"message": "Required"
}
]",
"message": "body/name Required",
"statusCode": 400,
}
`);
Expand All @@ -139,15 +119,7 @@ describe('response schema', () => {
{
"code": "FST_ERR_VALIDATION",
"error": "Bad Request",
"message": "body/ [
{
"code": "invalid_type",
"expected": "object",
"received": "null",
"path": [],
"message": "Expected object, received null"
}
]",
"message": "body/ Expected object, received null",
"statusCode": 400,
}
`);
Expand Down
6 changes: 6 additions & 0 deletions types/error.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import type { FastifySchemaValidationError } from 'fastify/types/schema';
import { expectAssignable } from 'tsd';

import type { ZodFastifySchemaValidationError } from '../src/errors';

expectAssignable<FastifySchemaValidationError>({} as ZodFastifySchemaValidationError);
Loading