Skip to content

Instantly share code, notes, and snippets.

@alex3165
Last active March 5, 2019 19:35
Show Gist options
  • Save alex3165/d9e4221c937b106ad227842069efd14b to your computer and use it in GitHub Desktop.
Save alex3165/d9e4221c937b106ad227842069efd14b to your computer and use it in GitHub Desktop.
import * as Ajv from 'ajv';
import swaggerDefinition from './my-swagger-definition';
import { Request, Response, NextFunction } from 'express';
const ajv = Ajv({ allErrors: true });
// validation middleware
const validateSchema = (schema: UserResSchema) => {
return (req: Request, res: Response, next: NextFunction) => {
const valid = ajv.validate(schema, req.body); // return boolean
if (!valid) {
res.send(new Error('Could not validate schema ' + schema.title));
}
next()
}
}
app.post('/users', validateSchema(swaggerDefinition.definitions.UserRes.schema), (req: Request, res: Response) => {
res.send(req.body).status(201).end();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment