From 424a86fe530b1d0d727272709b75f0c20d087d33 Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Mon, 4 May 2020 22:06:20 +0200 Subject: [PATCH] Validator: add custom value transform function for display + Version 0.4.22 --- package.json | 2 +- src/db/Validator.ts | 23 +++++++++++++++++++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index c39ce74..f581666 100644 --- a/package.json +++ b/package.json @@ -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 ", diff --git a/src/db/Validator.ts b/src/db/Validator.ts index cc79eca..275417e 100644 --- a/src/db/Validator.ts +++ b/src/db/Validator.ts @@ -7,9 +7,14 @@ export default class Validator { private readonly steps: ValidationStep[] = []; 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 { 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}.`; } }