@nestjs/core
Version:
The core of NestJS, a TypeScript framework for Node.js backends: modules, dependency injection and the request pipeline, on Express, Fastify or node:http.
40 lines (39 loc) • 1.42 kB
JavaScript
import { isObservable, lastValueFrom } from 'rxjs';
import { getClassRef } from '../helpers/class-ref-registry.js';
import { ExecutionContextHost } from '../helpers/execution-context-host.js';
import { isEmptyArray } from '@nestjs/common/internal';
export class GuardsConsumer {
async tryActivate(guards, args, instance, callback, type) {
if (!guards || isEmptyArray(guards)) {
return true;
}
const context = this.createContext(args, instance, callback);
context.setType(type);
for (const guard of guards) {
const result = guard.canActivate(context);
if (typeof result === 'boolean') {
if (!result) {
return false;
}
continue;
}
if (await this.pickResult(result)) {
continue;
}
return false;
}
return true;
}
createContext(args, instance, callback) {
return new ExecutionContextHost(args, getClassRef(instance), callback);
}
async pickResult(result) {
// "isObservable()" also recognises Observables created by another copy
// of rxjs, which are not instances of the "Observable" class imported here
const value = await result;
if (isObservable(value)) {
return lastValueFrom(value);
}
return value;
}
}