console-app/lib/TypeValidation/TypeValidation.ts
Timo Hocker 7ad999878a
All checks were successful
continuous-integration/drone/push Build is passing
fix for number input, new integer input
2020-07-19 11:41:06 +02:00

80 lines
2.3 KiB
TypeScript

/*
* Copyright (C) Sapphirecode - All Rights Reserved
* This file is part of console-app which is released under MIT.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, May 2020
*/
import { OptionType } from '../OptionType';
export class TypeValidation {
private readonly _option_type: string;
public get option_type (): OptionType {
return this._option_type as OptionType;
}
public get persistent_type (): 'string'|'number'|'boolean'|'array' {
return this.option_type as 'string'|'number'|'boolean'|'array';
}
public get string_type (): 'string'|'number'|'boolean'|'object' {
const type = this.option_type;
if (type === 'array')
return 'object';
return type as 'string'|'number'|'boolean';
}
public constructor (type: string) {
this._option_type = type;
}
public validate_type (value: unknown): boolean {
const type_match = typeof value === this.string_type;
const array_match = this.option_type !== 'array' || Array.isArray (value);
return type_match && array_match;
}
public to_type (value: unknown): Promise<unknown> {
if (this.option_type === 'string')
return Promise.resolve (String (value));
if (this.option_type === 'number') {
const as_num = parseFloat (String (value));
if (isNaN (as_num))
throw new Error ('value is not a number');
return Promise.resolve (as_num);
}
if (this.option_type === 'int') {
const as_num = parseInt (String (value));
if (isNaN (as_num))
throw new Error ('value is not a number');
return Promise.resolve (as_num);
}
if (this.option_type === 'boolean') {
const as_num = parseInt (String (value));
if (
as_num !== 1 && as_num !== 0
&& !(/^(?:true|false)$/iu).test (String (value))
)
throw new Error ('value is not a boolean');
return Promise.resolve (
as_num === 1 || (/true/iu).test (String (value))
);
}
if (this.option_type === 'array') {
if (typeof value === 'string') {
return Promise.resolve (value.split (',')
.map ((v) => v.trim ()));
}
if (this.validate_type (value))
return Promise.resolve (value);
throw new Error ('value is not an array');
}
throw new Error ('unknown type');
}
}