smartguard/ts/classes.guard.ts

36 lines
839 B
TypeScript

import * as plugins from './smartguard.plugins.js';
export type TGuardFunction<T> = (dataArg: T) => Promise<boolean>;
export interface IGuardOptions {
name?: string;
failedHint?: string;
}
export class Guard<T> {
private guardFunction: TGuardFunction<T>;
public options: IGuardOptions;
constructor(guardFunctionArg: TGuardFunction<T>, optionsArg?: IGuardOptions) {
this.guardFunction = guardFunctionArg;
this.options = optionsArg;
}
/**
* executes the guard against a data argument;
* @param dataArg
*/
public async exec(dataArg: T) {
const result = await this.guardFunction(dataArg);
return result;
}
public async getFailedHint(dataArg: T) {
const result = await this.exec(dataArg);
if (!result) {
return this.options.failedHint;
} else {
return null;
}
}
}