smartguard/ts/classes.guard.ts

36 lines
839 B
TypeScript
Raw Normal View History

2022-03-21 20:53:46 +00:00
import * as plugins from './smartguard.plugins.js';
2019-08-07 14:31:53 +00:00
export type TGuardFunction<T> = (dataArg: T) => Promise<boolean>;
2024-05-30 20:09:37 +00:00
export interface IGuardOptions {
name?: string;
failedHint?: string;
}
2019-08-07 14:31:53 +00:00
export class Guard<T> {
2019-08-07 14:34:34 +00:00
private guardFunction: TGuardFunction<T>;
2024-08-25 16:03:37 +00:00
public options: IGuardOptions;
2024-05-30 20:09:37 +00:00
constructor(guardFunctionArg: TGuardFunction<T>, optionsArg?: IGuardOptions) {
2019-08-07 14:31:53 +00:00
this.guardFunction = guardFunctionArg;
2024-08-25 16:03:37 +00:00
this.options = optionsArg;
2019-08-07 14:31:53 +00:00
}
/**
* executes the guard against a data argument;
* @param dataArg
*/
public async exec(dataArg: T) {
2019-08-07 14:31:53 +00:00
const result = await this.guardFunction(dataArg);
return result;
}
2024-05-30 20:09:37 +00:00
public async getFailedHint(dataArg: T) {
const result = await this.exec(dataArg);
if (!result) {
2024-08-25 16:03:37 +00:00
return this.options.failedHint;
2024-05-30 20:09:37 +00:00
} else {
return null;
}
}
2019-08-07 14:34:34 +00:00
}