smartguard/ts/classes.guardset.ts

88 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-03-21 20:53:46 +00:00
import * as plugins from './smartguard.plugins.js';
2024-08-25 16:03:37 +00:00
import { Guard, type TGuardFunction } from './classes.guard.js';
2019-08-07 14:31:53 +00:00
2024-05-30 20:09:37 +00:00
export interface IExecOptions {
mode?: 'parallel' | 'serial';
stopOnFail?: boolean;
}
2019-08-07 14:31:53 +00:00
/**
2024-05-30 14:57:18 +00:00
* Extended GuardSet that inherits from Guard
* and provides additional functionalities.
2019-08-07 14:31:53 +00:00
*/
2024-05-30 14:57:18 +00:00
export class GuardSet<T> extends Guard<T> {
2019-08-07 14:31:53 +00:00
public guards: Array<Guard<T>>;
2024-05-30 14:57:18 +00:00
constructor(guardArray: Array<Guard<T>> = []) {
super(async (dataArg: T) => {
return this.allGuardsPass(dataArg);
})
this.guards = guardArray;
2019-08-07 14:31:53 +00:00
}
2024-05-30 14:57:18 +00:00
/**
* executes all guards in all guardSets against a data argument
* @param dataArg
*/
2024-05-30 20:09:37 +00:00
public async execAllWithData(dataArg: T, optionsArg: IExecOptions = {
mode: 'parallel',
stopOnFail: false
}): Promise<boolean[]> {
2019-08-07 14:31:53 +00:00
const resultPromises: Array<Promise<boolean>> = [];
2024-05-30 14:57:18 +00:00
2019-08-07 14:31:53 +00:00
for (const guard of this.guards) {
const guardResultPromise = guard.exec(dataArg);
2024-05-30 20:09:37 +00:00
if (optionsArg.mode === 'serial') {
await guardResultPromise;
}
2024-05-30 14:57:18 +00:00
resultPromises.push(guardResultPromise);
2024-05-30 20:09:37 +00:00
if (optionsArg.stopOnFail) {
if (!await guardResultPromise) {
return await Promise.all(resultPromises);
}
}
2019-08-07 14:31:53 +00:00
}
2024-05-30 14:57:18 +00:00
const results = await Promise.all(resultPromises);
2019-08-07 14:31:53 +00:00
return results;
}
2024-05-30 14:57:18 +00:00
/**
* checks if all guards pass
* @param dataArg
*/
2024-05-30 20:09:37 +00:00
public async allGuardsPass(dataArg: T, optionsArg: IExecOptions = {
mode: 'parallel',
stopOnFail: false
}): Promise<boolean> {
const results = await this.execAllWithData(dataArg, optionsArg);
2024-05-30 14:57:18 +00:00
return results.every(result => result);
}
/**
* checks if any guard passes
* @param dataArg
*/
public async anyGuardsPass(dataArg: T): Promise<boolean> {
2024-05-30 20:09:37 +00:00
const results = await this.execAllWithData(dataArg, {
mode: 'parallel',
stopOnFail: false
});
2024-05-30 14:57:18 +00:00
return results.some(result => result);
}
2024-05-30 20:09:37 +00:00
/**
* returns the first reason for why something fails
* @param dataArg
* @returns
*/
public getFailedHint (dataArg: T): Promise<string> {
for (const guard of this.guards) {
const failedHint = guard.getFailedHint(dataArg);
if (failedHint) {
return failedHint;
}
}
}
2019-08-07 14:34:34 +00:00
}