smartguard/ts/smartguard.classes.guardset.ts
2024-05-30 16:57:18 +02:00

52 lines
1.4 KiB
TypeScript

import * as plugins from './smartguard.plugins.js';
import { Guard, type TGuardFunction } from './smartguard.classes.guard.js';
/**
* Extended GuardSet that inherits from Guard
* and provides additional functionalities.
*/
export class GuardSet<T> extends Guard<T> {
public guards: Array<Guard<T>>;
constructor(guardArray: Array<Guard<T>> = []) {
super(async (dataArg: T) => {
return this.allGuardsPass(dataArg);
})
this.guards = guardArray;
}
/**
* executes all guards in all guardSets against a data argument
* @param dataArg
*/
public async executeAllGuardsWithData(dataArg: T) {
const resultPromises: Array<Promise<boolean>> = [];
for (const guard of this.guards) {
const guardResultPromise = guard.executeGuardWithData(dataArg);
resultPromises.push(guardResultPromise);
}
const results = await Promise.all(resultPromises);
return results;
}
/**
* checks if all guards pass
* @param dataArg
*/
public async allGuardsPass(dataArg: T): Promise<boolean> {
const results = await this.executeAllGuardsWithData(dataArg);
return results.every(result => result);
}
/**
* checks if any guard passes
* @param dataArg
*/
public async anyGuardsPass(dataArg: T): Promise<boolean> {
const results = await this.executeAllGuardsWithData(dataArg);
return results.some(result => result);
}
}