-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
BaseSchema.ts
58 lines (58 loc) · 1.62 KB
/
BaseSchema.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { Key, Values, makeValues } from "../libs/types.ts";
import { ErrorHandler } from "../libs/publicTypes.ts";
import { ValueSchemaError } from "../libs/ValueSchemaError.ts";
interface Options {
}
type ApplyTo<T> = (values: Values, options: Options, keyStack: Key[]) => values is Values<T>;
/**
* Base Schema Class
*/
export class BaseSchema<T = unknown> {
private readonly options: Options;
private readonly applyToList: ApplyTo<T>[];
/**
* constructor
* @param options options
* @param applyToList list of applyTo
*/
constructor(options: Options, applyToList: ApplyTo<T>[]) {
this.options = options;
this.applyToList = applyToList;
}
/**
* apply schema
* @param value value to apply
* @param onError error handler
* @returns applied value
*/
applyTo(value: unknown, onError: ErrorHandler<T> = onErrorDefault): T {
return this._applyTo(value, onError, []);
}
private _applyTo(value: unknown, onError: ErrorHandler<T>, keyStack: Key[]): T {
try {
const values = makeValues(value);
for (const applyTo of this.applyToList) {
if (applyTo(values, this.options, keyStack)) {
return values.output;
}
}
return values.output as T;
}
catch (err) {
return onError(err);
}
}
}
/**
* default error handler
* @param err error object
*/
export function onErrorDefault(err: ValueSchemaError): never {
throw err;
}
/**
* default finish handler
*/
export function onFinishedDefault(): void {
// do nothing
}