frontend: Add run-serially.guard to execute multiple guards in sequence
This commit is contained in:
parent
24b39fd02f
commit
72b8a9d12f
@ -5,3 +5,4 @@ export * from './application-mode.guard';
|
||||
export * from './participant-name.guard';
|
||||
export * from './replace-moderator-secret.guard';
|
||||
export * from './room-creator.guard';
|
||||
export * from './run-serially.guard';
|
||||
|
||||
@ -0,0 +1,36 @@
|
||||
import { EnvironmentInjector, inject, runInInjectionContext } from '@angular/core';
|
||||
import { ActivatedRouteSnapshot, CanActivateFn, GuardResult, RouterStateSnapshot } from '@angular/router';
|
||||
import { isObservable, lastValueFrom } from 'rxjs';
|
||||
|
||||
/**
|
||||
* This guard is used to run multiple guards serially.
|
||||
*
|
||||
* @param guards List of guards to run serially.
|
||||
* @returns A guard that runs the provided guards serially.
|
||||
*/
|
||||
export const runGuardsSerially = (...guards: CanActivateFn[]): CanActivateFn => {
|
||||
return async (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
|
||||
const injector = inject(EnvironmentInjector);
|
||||
|
||||
for (const guard of guards) {
|
||||
const result = runInInjectionContext(injector, () => guard(route, state));
|
||||
let resolvedResult: GuardResult;
|
||||
|
||||
if (result instanceof Promise) {
|
||||
resolvedResult = await result;
|
||||
} else if (isObservable(result)) {
|
||||
resolvedResult = await lastValueFrom(result);
|
||||
} else {
|
||||
resolvedResult = result;
|
||||
}
|
||||
|
||||
if (typeof resolvedResult === 'boolean' && !resolvedResult) {
|
||||
return false;
|
||||
} else if (typeof resolvedResult !== 'boolean') {
|
||||
return resolvedResult;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user