@push.rocks/smartguard
Version:
A TypeScript library for creating and managing validation guards, aiding in data validation and security checks.
35 lines (29 loc) • 862 B
text/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): Promise<string | null> {
const result = await this.exec(dataArg);
if (!result) {
return this.options.failedHint || null;
}
return null;
}
}