swaf/src/db/Validator.ts

426 lines
12 KiB
TypeScript

import Model from "./Model";
import Query, {WhereTest} from "./Query";
import {Connection} from "mysql";
import {Type} from "../Utils";
export default class Validator<T> {
private readonly steps: ValidationStep<T>[] = [];
private readonly validationAttributes: string[] = [];
private readonly rawValueToHuman?: (val: T) => string;
private _min?: number;
private _max?: number;
public constructor(rawValueToHuman?: (val: T) => string) {
this.rawValueToHuman = rawValueToHuman;
}
/**
* @param thingName The name of the thing to validate.
* @param value The value to verify.
* @param onlyFormat {@code true} to only validate format properties, {@code false} otherwise.
* @param connection A connection to use in case of wrapped transactions.
*/
async execute(thingName: string, value: T | undefined, onlyFormat: boolean, connection?: Connection): Promise<void> {
const bag = new ValidationBag();
for (const step of this.steps) {
if (onlyFormat && !step.isFormat) continue;
const result = step.verifyStep(value, thingName, connection);
if ((result === false || result instanceof Promise && (await result) === false) && step.throw) {
const error: ValidationError = step.throw();
error.rawValueToHuman = this.rawValueToHuman;
error.thingName = thingName;
error.value = value;
bag.addMessage(error);
} else if (step.interrupt !== undefined && step.interrupt(value)) {
break;
}
}
if (bag.hasMessages()) {
throw bag;
}
}
public defined(): Validator<T> {
this.validationAttributes.push('required');
this.addStep({
verifyStep: val => val !== undefined,
throw: () => new UndefinedValueValidationError(),
isFormat: true,
});
return this;
}
public acceptUndefined(alsoAcceptEmptyString: boolean = false): Validator<T> {
this.addStep({
verifyStep: () => true,
throw: null,
interrupt: val => val === undefined || val === null || (alsoAcceptEmptyString && typeof val === 'string' && val.length === 0),
isFormat: true,
});
return this;
}
public equals(other?: T): Validator<T> {
this.addStep({
verifyStep: val => val === other,
throw: () => new BadValueValidationError(other),
isFormat: true,
});
return this;
}
public sameAs(otherName?: string, other?: T): Validator<T> {
this.addStep({
verifyStep: val => val === other,
throw: () => new DifferentThanError(otherName),
isFormat: true,
});
return this;
}
public regexp(regexp: RegExp): Validator<T> {
this.validationAttributes.push(`pattern="${regexp}"`);
this.addStep({
verifyStep: val => regexp.test(<string><unknown>val),
throw: () => new InvalidFormatValidationError(),
isFormat: true,
});
return this;
}
public length(length: number): Validator<T> {
this.addStep({
verifyStep: val => (<any>val).length === length,
throw: () => new BadLengthValidationError(length),
isFormat: true,
});
return this;
}
/**
* @param minLength included
*/
public minLength(minLength: number): Validator<T> {
this.addStep({
verifyStep: val => (<any>val).length >= minLength,
throw: () => new TooShortError(minLength),
isFormat: true,
});
return this;
}
/**
* @param maxLength included
*/
public maxLength(maxLength: number): Validator<T> {
this.addStep({
verifyStep: val => (<any>val).length <= maxLength,
throw: () => new TooLongError(maxLength),
isFormat: true,
});
return this;
}
/**
* @param minLength included
* @param maxLength included
*/
public between(minLength: number, maxLength: number): Validator<T> {
this.addStep({
verifyStep: val => {
const length = (<any>val).length;
return length >= minLength && length <= maxLength;
},
throw: () => new BadLengthValidationError(minLength, maxLength),
isFormat: true,
});
return this;
}
/**
* @param min included
*/
public min(min: number): Validator<T> {
this.validationAttributes.push(`min="${min}"`);
this._min = min;
this.addStep({
verifyStep: val => {
return (<any>val) >= min;
},
throw: () => new OutOfRangeValidationError(this._min, this._max),
isFormat: true,
});
return this;
}
/**
* @param max included
*/
public max(max: number): Validator<T> {
this.validationAttributes.push(`max="${max}"`);
this._max = max;
this.addStep({
verifyStep: val => {
return (<any>val) <= max;
},
throw: () => new OutOfRangeValidationError(this._min, this._max),
isFormat: true,
});
return this;
}
public unique<M extends Model>(model: M | Type<M>, foreignKey?: string, querySupplier?: () => Query): Validator<T> {
this.addStep({
verifyStep: async (val, thingName, c) => {
if (!foreignKey) foreignKey = thingName;
let query: Query;
if (querySupplier) {
query = querySupplier().where(foreignKey, val);
} else {
query = (model instanceof Model ? <any>model.constructor : model).select('1').where(foreignKey, val);
}
if (model instanceof Model && typeof model.id === 'number') query = query.where('id', model.id, WhereTest.NE);
return (await query.execute(c)).results.length === 0;
},
throw: () => new AlreadyExistsValidationError((<any>model).table),
isFormat: false,
});
return this;
}
public exists(modelClass: Function, foreignKey?: string): Validator<T> {
this.addStep({
verifyStep: async (val, thingName, c) => (await (<any>modelClass).select('1').where(foreignKey !== undefined ? foreignKey : thingName, val).execute(c)).results.length >= 1,
throw: () => new UnknownRelationValidationError((<any>modelClass).table, foreignKey),
isFormat: false,
});
return this;
}
private addStep(step: ValidationStep<T>) {
this.steps.push(step);
}
public getValidationAttributes(): string[] {
return this.validationAttributes;
}
public step(step: number): Validator<T> {
this.validationAttributes.push(`step="${step}"`);
return this;
}
}
interface ValidationStep<T> {
interrupt?: (val?: T) => boolean;
verifyStep(val: T | undefined, thingName: string, connection?: Connection): boolean | Promise<boolean>;
throw: ((val?: T) => ValidationError) | null;
readonly isFormat: boolean;
}
export class ValidationBag extends Error {
private readonly errors: ValidationError[] = [];
public addMessage(err: ValidationError) {
if (!err.thingName) throw new Error('Null thing name');
this.errors.push(err);
}
public addBag(otherBag: ValidationBag) {
for (const error of otherBag.errors) {
this.errors.push(error);
}
}
public hasMessages(): boolean {
return this.errors.length > 0;
}
public getMessages(): { [p: string]: ValidationError } {
const messages: { [p: string]: ValidationError } = {};
for (const err of this.errors) {
messages[err.thingName!] = {
name: err.name,
message: err.message,
value: err.value,
};
}
return messages;
}
public getErrors(): ValidationError[] {
return this.errors;
}
}
export abstract class ValidationError extends Error {
public rawValueToHuman?: (val: any) => string;
public thingName?: string;
public value?: any;
public get name(): string {
return this.constructor.name;
}
}
export class BadLengthValidationError extends ValidationError {
private readonly expectedLength: number;
private readonly maxLength?: number;
constructor(expectedLength: number, maxLength?: number) {
super();
this.expectedLength = expectedLength;
this.maxLength = maxLength;
}
public get message(): string {
return `${this.thingName} expected length: ${this.expectedLength}${this.maxLength !== undefined ? ` to ${this.maxLength}` : ''}; ` +
`actual length: ${this.value.length}.`;
}
}
export class TooShortError extends ValidationError {
private readonly minLength: number;
constructor(minLength: number) {
super();
this.minLength = minLength;
}
public get message(): string {
return `${this.thingName} must be at least ${this.minLength} characters.`;
}
}
export class TooLongError extends ValidationError {
private readonly maxLength: number;
constructor(maxLength: number) {
super();
this.maxLength = maxLength;
}
public get message(): string {
return `${this.thingName} must be at most ${this.maxLength} characters.`;
}
}
export class BadValueValidationError extends ValidationError {
private readonly expectedValue: any;
constructor(expectedValue: any) {
super();
this.expectedValue = expectedValue;
}
public get message(): string {
let expectedValue = this.expectedValue;
let actualValue = this.value;
if (this.rawValueToHuman) {
expectedValue = this.rawValueToHuman(expectedValue);
actualValue = this.rawValueToHuman(actualValue);
}
return `Expected: ${expectedValue}; got: ${actualValue}.`
}
}
export class DifferentThanError extends ValidationError {
private readonly otherName: any;
constructor(otherName: any) {
super();
this.otherName = otherName;
}
public get message(): string {
return `This should be the same as ${this.otherName}.`
}
}
export class OutOfRangeValidationError extends ValidationError {
private readonly min?: number;
private readonly max?: number;
constructor(min?: number, max?: number) {
super();
this.min = min;
this.max = max;
}
public get message(): string {
if (this.min === undefined) {
return `${this.thingName} must be at most ${this.max}`;
} else if (this.max === undefined) {
return `${this.thingName} must be at least ${this.min}`;
}
let min: any = this.min;
let max: any = this.max;
if (this.rawValueToHuman) {
min = this.rawValueToHuman(min);
max = this.rawValueToHuman(max);
}
return `${this.thingName} must be between ${min} and ${max}.`;
}
}
export class InvalidFormatValidationError extends ValidationError {
public get message(): string {
return `"${this.value}" is not a valid ${this.thingName}.`;
}
}
export class UndefinedValueValidationError extends ValidationError {
public get message(): string {
return `${this.thingName} is required.`;
}
}
export class AlreadyExistsValidationError extends ValidationError {
private readonly table: string;
constructor(table: string) {
super();
this.table = table;
}
public get message(): string {
return `${this.thingName} already exists in ${this.table}.`;
}
}
export class UnknownRelationValidationError extends ValidationError {
private readonly table: string;
private readonly foreignKey?: string;
constructor(table: string, foreignKey?: string) {
super();
this.table = table;
this.foreignKey = foreignKey;
}
public get message(): string {
return `${this.thingName}=${this.value} relation was not found in ${this.table}${this.foreignKey !== undefined ? `.${this.foreignKey}` : ''}.`;
}
}
export class FileError extends ValidationError {
private readonly m: string;
constructor(message: string) {
super();
this.m = message;
}
public get message(): string {
return `${this.m}`;
}
}