Files
smartguard/ts/classes.guard.ts

36 lines
839 B
TypeScript
Raw Permalink Normal View History

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