1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.InterceptorsConsumer = void 0;
|
4 | const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
|
5 | const rxjs_1 = require("rxjs");
|
6 | const operators_1 = require("rxjs/operators");
|
7 | const execution_context_host_1 = require("../helpers/execution-context-host");
|
8 | class InterceptorsConsumer {
|
9 | async intercept(interceptors, args, instance, callback, next, type) {
|
10 | if ((0, shared_utils_1.isEmpty)(interceptors)) {
|
11 | return next();
|
12 | }
|
13 | const context = this.createContext(args, instance, callback);
|
14 | context.setType(type);
|
15 | const start$ = (0, rxjs_1.defer)(() => this.transformDeferred(next));
|
16 | const nextFn = (i = 0) => async () => {
|
17 | if (i >= interceptors.length) {
|
18 | return start$;
|
19 | }
|
20 | const handler = {
|
21 | handle: () => (0, rxjs_1.from)(nextFn(i + 1)()).pipe((0, operators_1.mergeAll)()),
|
22 | };
|
23 | return interceptors[i].intercept(context, handler);
|
24 | };
|
25 | return nextFn()();
|
26 | }
|
27 | createContext(args, instance, callback) {
|
28 | return new execution_context_host_1.ExecutionContextHost(args, instance.constructor, callback);
|
29 | }
|
30 | transformDeferred(next) {
|
31 | return (0, rxjs_1.from)(next()).pipe((0, operators_1.switchMap)(res => {
|
32 | const isDeferred = res instanceof Promise || res instanceof rxjs_1.Observable;
|
33 | return isDeferred ? res : Promise.resolve(res);
|
34 | }));
|
35 | }
|
36 | }
|
37 | exports.InterceptorsConsumer = InterceptorsConsumer;
|