-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Labels
documentationImprovements or additions to documentationImprovements or additions to documentation
Description
🚀 Feature Proposal
Ajv supports async schema with ability to define your own keywords for validation. But Fastify is not handling async validation properly.
Motivation
My motivation is to clearly define all request validations in one place (in schema).
Example
const Ajv = require('ajv');
const fastify = require('fastify');
const app = fastify({});
const ajv = new Ajv({
removeAdditional: true,
useDefaults: true,
coerceTypes: true,
nullable: true,
});
ajv.addKeyword('validator', {
async: true,
errors: false,
validate: (schema, data) => new Promise(
(resolve) => console.log(schema, data) || resolve(false)
),
});
app.setValidatorCompiler(({ schema }) => ajv.compile(schema));
app.get('/', {
schema: {
description: 'Tests if server is working.',
query: {
$async: true,
type: 'object',
properties: {
data: {
type: 'string',
validator: 'custom:validator',
},
},
},
},
handler: (req, res) => console.log(req.query) || res.send('ok'),
});
app.listen(8000, (err) => {
if (err) throw err;
});Send test query
❯ curl http://localhost:8000/?data=test
okLogs of the query
❯ node testFastify.js
custom:validator asd
[Object: null prototype] { data: 'asd' }
(node:28661) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:28661) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
documentationImprovements or additions to documentationImprovements or additions to documentation