Validator: add custom value transform function for display

+ Version 0.4.22
This commit is contained in:
Alice Gaudon 2020-05-04 22:06:20 +02:00
parent 0591daf93f
commit 424a86fe53
2 changed files with 22 additions and 3 deletions

View File

@ -1,6 +1,6 @@
{
"name": "wms-core",
"version": "0.4.21",
"version": "0.4.22",
"description": "Node web framework",
"repository": "git@gitlab.com:ArisuOngaku/wms-core.git",
"author": "Alice Gaudon <alice@gaudon.pro>",

View File

@ -7,9 +7,14 @@ 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.
@ -25,6 +30,7 @@ export default class Validator<T> {
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);
@ -256,6 +262,7 @@ export class ValidationBag extends Error {
}
export abstract class ValidationError extends Error {
public rawValueToHuman?: (val: any) => string;
public thingName?: string;
public value?: any;
@ -315,7 +322,13 @@ export class BadValueValidationError extends ValidationError {
}
public get message(): string {
return `Expected: ${this.expectedValue}; got: ${this.value}.`
let expectedValue = this.expectedValue;
let actualValue = this.value;
if (this.rawValueToHuman) {
expectedValue = this.rawValueToHuman(expectedValue);
actualValue = this.rawValueToHuman(actualValue);
}
return `Expected: ${expectedValue}; got: ${actualValue}.`
}
}
@ -348,7 +361,13 @@ export class OutOfRangeValidationError extends ValidationError {
} else if (this.max === undefined) {
return `${this.thingName} must be at least ${this.min}`;
}
return `${this.thingName} must be between ${this.min} and ${this.max}.`;
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}.`;
}
}