Move Controller.validate to static Validator.validate

This commit is contained in:
Alice Gaudon 2020-11-11 18:37:39 +01:00
parent bb8b44b5a3
commit b8905ea02b
2 changed files with 20 additions and 20 deletions

View File

@ -2,7 +2,6 @@ import express, {IRouter, RequestHandler, Router} from "express";
import {PathParams} from "express-serve-static-core"; import {PathParams} from "express-serve-static-core";
import config from "config"; import config from "config";
import {log} from "./Logger"; import {log} from "./Logger";
import Validator, {ValidationBag} from "./db/Validator";
import FileUploadMiddleware from "./FileUploadMiddleware"; import FileUploadMiddleware from "./FileUploadMiddleware";
import * as querystring from "querystring"; import * as querystring from "querystring";
import {ParsedUrlQueryInput} from "querystring"; import {ParsedUrlQueryInput} from "querystring";
@ -171,25 +170,6 @@ export default abstract class Controller {
} }
} }
protected async validate(
validationMap: { [p: string]: Validator<unknown> },
body: { [p: string]: unknown },
): Promise<void> {
const bag = new ValidationBag();
for (const p of Object.keys(validationMap)) {
try {
await validationMap[p].execute(p, body[p], false);
} catch (e) {
if (e instanceof ValidationBag) {
bag.addBag(e);
} else throw e;
}
}
if (bag.hasMessages()) throw bag;
}
protected getApp(): Application { protected getApp(): Application {
if (!this.app) throw new Error('Application not initialized.'); if (!this.app) throw new Error('Application not initialized.');
return this.app; return this.app;

View File

@ -6,6 +6,26 @@ import {ServerError} from "../HttpError";
export const EMAIL_REGEX = /^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/; export const EMAIL_REGEX = /^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/;
export default class Validator<V> { export default class Validator<V> {
public static async validate(
validationMap: { [p: string]: Validator<unknown> },
body: { [p: string]: unknown },
): Promise<void> {
const bag = new ValidationBag();
for (const p of Object.keys(validationMap)) {
try {
await validationMap[p].execute(p, body[p], false);
} catch (e) {
if (e instanceof ValidationBag) {
bag.addBag(e);
} else throw e;
}
}
if (bag.hasMessages()) throw bag;
}
private readonly steps: ValidationStep<V>[] = []; private readonly steps: ValidationStep<V>[] = [];
private readonly validationAttributes: string[] = []; private readonly validationAttributes: string[] = [];