Last active
March 5, 2019 19:35
-
-
Save alex3165/d9e4221c937b106ad227842069efd14b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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