console-app/lib/TypeValidation/TypeValidation.ts

80 lines
2.3 KiB
TypeScript
Raw Permalink Normal View History

2020-05-15 16:53:45 +02:00
/*
* 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
*/
2020-05-09 21:30:37 +02:00
import { OptionType } from '../OptionType';
2020-05-09 19:51:43 +02:00
export class TypeValidation {
2020-05-09 21:30:37 +02:00
private readonly _option_type: string;
public get option_type (): OptionType {
return this._option_type as OptionType;
}
2020-05-09 19:51:43 +02:00
2020-05-09 21:30:37 +02:00
public get persistent_type (): 'string'|'number'|'boolean'|'array' {
return this.option_type as 'string'|'number'|'boolean'|'array';
2020-05-09 19:51:43 +02:00
}
2020-05-09 21:30:37 +02:00
public get string_type (): 'string'|'number'|'boolean'|'object' {
const type = this.option_type;
if (type === 'array')
return 'object';
return type as 'string'|'number'|'boolean';
2020-05-09 19:51:43 +02:00
}
public constructor (type: string) {
2020-05-09 21:30:37 +02:00
this._option_type = type;
2020-05-09 19:51:43 +02:00
}
public validate_type (value: unknown): boolean {
2020-05-09 21:30:37 +02:00
const type_match = typeof value === this.string_type;
const array_match = this.option_type !== 'array' || Array.isArray (value);
return type_match && array_match;
2020-05-09 19:51:43 +02:00
}
public to_type (value: unknown): Promise<unknown> {
2020-05-09 21:30:37 +02:00
if (this.option_type === 'string')
2020-05-09 19:51:43 +02:00
return Promise.resolve (String (value));
2020-05-09 21:30:37 +02:00
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') {
2020-05-09 19:51:43 +02:00
const as_num = parseInt (String (value));
if (isNaN (as_num))
throw new Error ('value is not a number');
return Promise.resolve (as_num);
}
2020-05-09 21:30:37 +02:00
if (this.option_type === 'boolean') {
2020-05-09 19:51:43 +02:00
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))
);
}
2020-05-09 21:30:37 +02:00
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');
}
2020-05-09 19:51:43 +02:00
throw new Error ('unknown type');
}
}