@nestjs/common#CallHandler TypeScript Examples

The following examples show how to use @nestjs/common#CallHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: logging.interceptor.ts    From 42_checkIn with GNU General Public License v3.0 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const now = Date.now();
    return next
      .handle()
      .pipe(
        tap(() =>
          this.logger.log(
            context.switchToHttp().getRequest().route.path,
            context.getHandler().name,
            Date.now() - now + 'ms',
          ),
        ),
      );
  }
Example #2
Source File: idempotent-subscriber.interceptor.ts    From pebula-node with MIT License 6 votes vote down vote up
intercept(context: SbContext, next: CallHandler) {
    const msg = context.getMessage();
    return from(this.checkProvision(context))
      .pipe(
        switchMap( provision => {
          switch (provision) {
            case IdempotentProvision.passThrough:
              return next.handle();
            case IdempotentProvision.exists:
              return of(context).pipe(completeMessage());
            case IdempotentProvision.create:
              return next.handle()
                .pipe( switchMap(() => this.adapter.create(context)) );
          }
        }),
      );
  }
Example #3
Source File: back-off.interceptor.ts    From pebula-node with MIT License 6 votes vote down vote up
intercept(context: SbContext, next: CallHandler) {
    const { retryCount, retryCountKey } = this.config;
    const msg = context.getMessage();
    const currentRetryCount = extractRetryCount(retryCountKey, msg) || 0;

    if (currentRetryCount > retryCount) {
      this.logger.log(`Message exceeded back-off retry [ MAX: ${retryCount}, ACTUAL: ${currentRetryCount} ]`);
      return of(context).pipe(abandonMessage(), block());
    } else {
      return next.handle()
        .pipe(
          catchError( (error, caught) => {
            const { backOffDelay, message } = createBackoffClone(currentRetryCount, msg, this.config);

            this.logger.log(`Message back-off iteration ${currentRetryCount}, calculated back-off delay: ${backOffDelay}, scheduled to: ${message.scheduledEnqueueTimeUtc.toUTCString()}`);

            return from(context.resolveClient().send(message))
              .pipe(
                mapTo(context),
                completeMessage(),
                block(),
              );
          }),
        );
    }
  }
Example #4
Source File: apm.interceptor.ts    From office-hours with GNU General Public License v3.0 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    this.addRouteToSentry(context);
    return next.handle().pipe(
      catchError((error) => {
        Sentry.captureException(error);
        throw error;
      }),
    );
  }
Example #5
Source File: transform.interceptor.ts    From nestjs-starter with MIT License 6 votes vote down vote up
intercept(ctx: ExecutionContext, next: CallHandler): Observable<Response<T>> {
    return next.handle().pipe(
      map((data) => ({
        statusCode: ctx.switchToHttp().getResponse().statusCode,
        message: data?.message || 'Success response',
        data: data?.output ?? data ?? null,
      })),
    );
  }
Example #6
Source File: webhook.interceptor.ts    From radiopanel with GNU General Public License v3.0 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
		const webhookName = this.reflector.get<string>('webhook', context.getHandler());
		const request = context.switchToHttp().getRequest() as IncomingMessage;

		if (!webhookName) {
			return next.handle();
		}

		return next.handle()
			.pipe(
				map((data) => {
					this.webhookService.executeWebhook(webhookName, data)

					return data;
				})
			)
	}
Example #7
Source File: audit-log.interceptor.ts    From radiopanel with GNU General Public License v3.0 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
		const eventName = this.reflector.get<string>('auditLog', context.getHandler());
		const request = context.switchToHttp().getRequest() as IncomingMessage & { user: any };
		const body = context.switchToHttp().getRequest()?.body || null;

		if (!eventName) {
			return next.handle();
		}

		this.auditLogService.log(request.user?.uuid, eventName, body, {
			method: request.method,
			url: request.url,
		});

		return next.handle();
	}
Example #8
Source File: NestHttpLoggingInterceptor.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
public intercept(context: ExecutionContext, next: CallHandler): Observable<CoreApiResponse<void>> {
    const request: Request = context.switchToHttp().getRequest();
    const requestStartDate: number = Date.now();
    
    return next.handle().pipe(tap((): void => {
      const requestFinishDate: number = Date.now();
      
      const message: string =
        `Method: ${request.method}; ` +
        `Path: ${request.path}; ` +
        `SpentTime: ${requestFinishDate - requestStartDate}ms`;
      
      Logger.log(message, NestHttpLoggingInterceptor.name);
    }));
  }
Example #9
Source File: logging.interceptor.ts    From Phantom with MIT License 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const now = Date.now();
    const req = context.switchToHttp().getRequest();

    const method = req.method;
    const url = req.url;

    return next
      .handle()
      .pipe(
        tap(() =>
          Logger.log(
            `${method} ${url} ${Date.now() - now}ms`,
            context.getClass().name,
          ),
        ),
      );
  }
Example #10
Source File: logging.interceptor.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();
    const method = request.method;
    const ctx = createRequestContext(request);

    const now = Date.now();
    return next.handle().pipe(
      tap(() => {
        const response = context.switchToHttp().getResponse();
        const statusCode = response.statusCode;

        const responseTime = Date.now() - now;

        const resData = { method, statusCode, responseTime };

        this.appLogger.log(ctx, 'Request completed', { resData });
      }),
    );
  }
Example #11
Source File: logging.interceptor.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest()
    const method = request.method
    const url = request.originalUrl
    const requestID = request.headers[REQUEST_ID_TOKEN_HEADER]

    this.appLogger.log({ method, requestID, url })

    const now = Date.now()
    return next.handle().pipe(
      tap(() => {
        const response = context.switchToHttp().getResponse()
        const statusCode = response.statusCode

        const responseTime = Date.now() - now
        this.appLogger.log({ method, requestID, url, statusCode, responseTime })
      })
    )
  }
Example #12
Source File: zlibjson.interceptor.ts    From emutypekov with GNU General Public License v3.0 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    this.logger.debug('=> Response is zlib compressed.');
    const response: Response = context.switchToHttp().getResponse();
    const request: Request = context.switchToHttp().getRequest();

    console.log('Request:');
    console.log(request.body);

    response.setHeader('Content-Type', 'application/json');

    return next.handle().pipe(
      map(async (body) => {
        console.log('Response:');
        console.log(body);
        response.end(await _deflate(IO.cleanString(JSON.stringify(body))));
      }),
    );
  }
Example #13
Source File: system.interceptor.ts    From emutypekov with GNU General Public License v3.0 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const req = context.getArgByIndex(0);
    this.logger.debug(
      `${context.getType()}: ${req.socket.remoteAddress} => Request: ${
        req.url
      }`,
    );

    const response: Response = context.switchToHttp().getResponse();

    response.setHeader('X-Powered-By', 'EmuTypekov');
    response.setHeader('Set-Cookie', 'PHPSESSID=undefined');

    return next.handle().pipe(
      map((body) => {
        return body;
      }),
    );
  }
Example #14
Source File: datadog.interceptor.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
intercept(
    context: ExecutionContext,
    next: CallHandler<unknown>,
  ): Observable<unknown> {
    const start = new Date().getTime();
    return next.handle().pipe(
      tap(() => {
        const duration = new Date().getTime() - start;

        const request = context.switchToHttp().getRequest<Request>();
        if (!request) {
          return;
        }

        this.datadogService.timing('requests.success', duration, {
          method: request.method,
          path: request.path,
        });
      }),
      catchError((error: Error) => {
        let method = 'no-method';
        let path = 'no-path';

        const request = context.switchToHttp().getRequest<Request>();
        if (request) {
          method = request.method;
          path = request.path;
        }

        this.datadogService.increment('requests.error', 1, {
          method,
          path,
          type: error.constructor.name,
        });

        return throwError(() => error);
      }),
    );
  }
Example #15
Source File: inject-context.interceptor.ts    From amplication with Apache License 2.0 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler) {
    const handler = context.getHandler();
    const graphqlContext = GqlExecutionContext.create(context);
    const { req } = graphqlContext.getContext();
    const args = graphqlContext.getArgs();

    const params = this.getInjectContextValueParameters(handler);

    if (!params) {
      return next.handle();
    }

    const { parameterPath, parameterType } = params;

    const parameterValue = this.getInjectableContextValue(
      req.user,
      parameterType
    );

    set(args, parameterPath, parameterValue);

    return next.handle();
  }
Example #16
Source File: aclFilterResponse.interceptor.ts    From amplication with Apache License 2.0 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const [permissionsRoles]: any = this.reflector.getAllAndMerge<string[]>(
      "roles",
      [context.getHandler(), context.getClass()]
    );

    const permission = this.rolesBuilder.permission({
      role: permissionsRoles.role,
      action: permissionsRoles.action,
      possession: permissionsRoles.possession,
      resource: permissionsRoles.resource,
    });

    return next.handle().pipe(
      map((data) => {
        if (Array.isArray(data)) {
          return data.map((results: any) => permission.filter(results));
        } else {
          return permission.filter(data);
        }
      })
    );
  }
Example #17
Source File: gcloud-storage-files.interceptor.ts    From nestjs-gcloud-storage with MIT License 6 votes vote down vote up
export function GCloudStorageFilesInterceptor(
  fieldName: string,
  localOptions?: MulterOptions,
  gcloudStorageOptions?: Partial<GCloudStoragePerRequestOptions>,
): Type<NestInterceptor> {
  @Injectable()
  class MixinInterceptor implements NestInterceptor {
    public interceptor: NestInterceptor;

    constructor(private readonly gcloudStorage: GCloudStorageService) {
      this.interceptor = new (FilesInterceptor(fieldName, 20, localOptions))();
    }

    async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
      (await this.interceptor.intercept(context, next)) as Observable<any>;

      const request = context.switchToHttp().getRequest();

      const files = request[fieldName];

      if (!files.length) {
        Logger.error(
          'GCloudStorageFilesInterceptor',
          `Can not intercept field "${fieldName}". Did you specify the correct field name in @GCloudStorageFilesInterceptor('${fieldName}')?`,
        );
        return;
      }

      for (const file of files) file.storageUrl = await this.gcloudStorage.upload(file, gcloudStorageOptions);

      return next.handle();
    }
  }

  const Interceptor = mixin(MixinInterceptor);
  return Interceptor as Type<NestInterceptor>;
}
Example #18
Source File: gcloud-stroage-file.interceptor.ts    From nestjs-gcloud-storage with MIT License 6 votes vote down vote up
export function GCloudStorageFileInterceptor(
  fieldName: string,
  localOptions?: MulterOptions,
  gcloudStorageOptions?: Partial<GCloudStoragePerRequestOptions>,
): Type<NestInterceptor> {
  @Injectable()
  class MixinInterceptor implements NestInterceptor {
    public interceptor: NestInterceptor;

    constructor(private readonly gcloudStorage: GCloudStorageService) {
      this.interceptor = new (FileInterceptor(fieldName, localOptions))();
    }

    async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
      (await this.interceptor.intercept(context, next)) as Observable<any>;

      const request = context.switchToHttp().getRequest();
      const file = request[fieldName];

      if (!file) {
        Logger.error(
          'GCloudStorageFileInterceptor',
          `Can not intercept field "${fieldName}". Did you specify the correct field name in @GCloudStorageFileInterceptor('${fieldName}')?`,
        );
        return;
      }

      const storageUrl = await this.gcloudStorage.upload(file, gcloudStorageOptions);
      file.storageUrl = storageUrl;
      return next.handle();
    }
  }

  const Interceptor = mixin(MixinInterceptor);
  return Interceptor as Type<NestInterceptor>;
}
Example #19
Source File: log.interceptor.ts    From nestjs-mercurius with MIT License 6 votes vote down vote up
intercept(
    context: ExecutionContext,
    next: CallHandler<any>,
  ): Observable<any> {
    const ctx = GqlExecutionContext.create(context);

    this.logger.warn(
      `Before - ${ctx.getClass().name}@${ctx.getHandler().name}`,
    );

    return next
      .handle()
      .pipe(
        tap(() =>
          this.logger.warn(
            `After - ${ctx.getClass().name}@${ctx.getHandler().name}`,
          ),
        ),
      );
  }
Example #20
Source File: serialization.interceptor.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map((args) => {
        const SerializeType = getSerializeType(context.getHandler());
        const entity = new SerializeType();
        if (Array.isArray(args)) {
          return Object.assign(entity, { data: args });
        } else {
          return Object.assign(entity, args);
        }
      }),
    );
  }
Example #21
Source File: wrap-response.interceptor.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map((...args) => {
        return {
          data: args[0].data ?? args[0],
        };
      }),
    );
  }
Example #22
Source File: wrap-response.interceptor.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map((...args) => {
        return {
          data: args[0].data ?? args[0],
        };
      }),
    );
  }
Example #23
Source File: wrap-response.interceptor.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map((...args) => {
        // if this an error response then return first object if no then second..
        return {
          data: args[0],
        };
      }),
    );
  }
Example #24
Source File: serialization.interceptor.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map((args) => {
        const SerializeType = getSerializeType(context.getHandler());
        const entity = new SerializeType();
        return Object.assign(entity, args);
      }),
    );
  }
Example #25
Source File: wrap-response.interceptor.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map((...args) => {
        const serializeOptions: any = {};
        const { data, options, collectionName } = args[0];

        if (data && collectionName) {
          if (data.length) {
            serializeOptions.attributes = Object.keys(_.omit(data[0], ['_id', 'id']));
            data.forEach((item: any) => {
              // eslint-disable-next-line no-param-reassign
              item.id = item._id;
              // eslint-disable-next-line no-param-reassign
              delete item._id;
            });
          } else {
            serializeOptions.attributes = Object.keys(_.omit(data, ['_id', 'id']));
          }
          if (options) {
            serializeOptions.topLevelLinks = PaginationUtils.getPaginationLinks(
              options.location,
              options.paginationParams,
              options.totalCount,
            );
            serializeOptions.meta = { totalCount: options.totalCount };
          }

          return new Serializer(collectionName, serializeOptions).serialize(data);
        }

        return {
          data: args[0].data ?? args[0],
        };
      }),
    );
  }
Example #26
Source File: wrap-response.interceptor.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map((...args) => {
        const serializeOptions: any = {};
        const { data, options, collectionName } = args[0];

        if (data && collectionName) {
          if (data.length) {
            serializeOptions.attributes = Object.keys(_.omit(data[0], ['_id', 'id']));
            data.forEach((item: any) => {
              // eslint-disable-next-line no-param-reassign
              item.id = item._id;
              // eslint-disable-next-line no-param-reassign
              delete item._id;
            });
          } else {
            serializeOptions.attributes = Object.keys(_.omit(data, ['_id', 'id']));
          }
          if (options) {
            serializeOptions.topLevelLinks = PaginationUtils.getPaginationLinks(
              options.location,
              options.paginationParams,
              options.totalCount,
            );
            serializeOptions.meta = { totalCount: options.totalCount };
          }

          return new Serializer(collectionName, serializeOptions).serialize(data);
        }

        return {
          data: args[0].data ?? args[0],
        };
      }),
    );
  }
Example #27
Source File: exception.interceptor.ts    From domain-driven-hexagon with MIT License 6 votes vote down vote up
intercept(
    _context: ExecutionContext,
    next: CallHandler,
  ): Observable<ExceptionBase> {
    return next.handle().pipe(
      catchError(err => {
        /**
         * Custom exceptions are converted to nest.js exceptions.
         * This way we are not tied to a framework or HTTP protocol.
         */
        if (err instanceof NotFoundException) {
          throw new NestNotFoundException(err.message);
        }
        if (err instanceof ConflictException) {
          throw new NestConflictException(err.message);
        }
        return throwError(err);
      }),
    );
  }
Example #28
Source File: aclValidateRequest.interceptor.ts    From amplication with Apache License 2.0 6 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const [permissionsRoles]: any = this.reflector.getAllAndMerge<string[]>(
      "roles",
      [context.getHandler(), context.getClass()]
    );

    const type = context.getType();

    const inputDataToValidate =
      type === "http"
        ? context.switchToHttp().getRequest().body
        : context.getArgByIndex(1).data;

    const permission = this.rolesBuilder.permission({
      role: permissionsRoles.role,
      action: permissionsRoles.action,
      possession: permissionsRoles.possession,
      resource: permissionsRoles.resource,
    });

    const invalidAttributes = abacUtil.getInvalidAttributes(
      permission,
      inputDataToValidate
    );

    if (invalidAttributes.length) {
      throw new ForbiddenException(
        "Insufficient privileges to complete the operation"
      );
    }

    return next.handle();
  }
Example #29
Source File: no-response-body.interceptor.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(map((data) => (data === undefined ? {} : data)))
  }