epic_explorer/server/middlewares/validator.middleware.ts

39 lines
1.1 KiB
TypeScript
Raw Normal View History

2019-07-09 09:22:36 +00:00
import { plainToClass } from 'class-transformer';
import { validate, ValidationError } from 'class-validator';
import * as express from 'express';
import { NextFunction, Request, Response } from 'express';
import { HttpException } from '../exceptions/index';
2019-08-14 10:55:23 +00:00
import { Global } from "../global";
2019-07-09 09:22:36 +00:00
export function validationMiddleware<T>(
type: any,
skipMissingProperties = false,
): express.RequestHandler {
return (request: Request, response: Response, next: NextFunction) => {
2019-08-16 13:06:07 +00:00
if(request.headers.network){
Global.network = request.headers.network;
}else{
Global.network = 'Floonet';
}
2019-07-09 09:22:36 +00:00
validate(
plainToClass(type, {
...request.body,
...request.query,
...request.params,
}),
{
skipMissingProperties,
},
).then((errors: ValidationError[]) => {
if (errors.length > 0) {
const message = errors.map((error: ValidationError) =>
Object.values(error.constraints),
);
next(new HttpException(400, message));
} else {
next();
}
});
};
}