console-app/lib/Types/TypeValidation.ts
2020-05-09 21:30:37 +02:00

66 lines
1.9 KiB
TypeScript

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 = 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');
}
}