UNPKG

@rxap/nest-open-api

Version:

This package provides tools and utilities for integrating OpenAPI specifications into NestJS applications. It includes features for handling upstream API requests, managing server configurations, and generating OpenAPI documentation. It also offers interc

49 lines (48 loc) 2.58 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ValidatorInterceptor = void 0; const tslib_1 = require("tslib"); const common_1 = require("@nestjs/common"); const nest_utilities_1 = require("@rxap/nest-utilities"); const class_validator_1 = require("class-validator"); const rxjs_1 = require("rxjs"); let ValidatorInterceptor = class ValidatorInterceptor { /** * Intercepts the execution of a method and performs validation on the response body. * If the class type of the execution context is 'HealthController' or 'AppController', * the method execution continues without any validation. * Otherwise, the method first retrieves the HTTP request from the execution context, * then executes the next handler and intercepts the response body. * If the response body is not null, it performs validation on it using the `validateSync` method. * If validation fails, it logs an error message, logs the response body, and throws a `ValidationHttpException`. * * @param {ExecutionContext} context - The execution context of the intercepted method. * @param {CallHandler<Response>} next - The next handler in the execution chain. * @returns {Observable<any>} - An observable that emits the response or throws a `ValidationHttpException`. */ intercept(context, next) { const classType = context.getClass(); if (classType.name === 'HealthController' || classType.name === 'AppController') { return next.handle(); } const request = context.switchToHttp().getRequest(); return next.handle().pipe((0, rxjs_1.tap)(body => { if (body) { const resultList = (0, class_validator_1.validateSync)(body); if (resultList.length) { this.logger.error(`Response for ${request.url}: ${(0, nest_utilities_1.ValidationErrorListToString)(resultList)}`, classType.name); this.logger.verbose(JSON.stringify(body), classType.name); throw new nest_utilities_1.ValidationHttpException(resultList, common_1.HttpStatus.INTERNAL_SERVER_ERROR); } } })); } }; exports.ValidatorInterceptor = ValidatorInterceptor; tslib_1.__decorate([ (0, common_1.Inject)(common_1.Logger), tslib_1.__metadata("design:type", common_1.Logger) ], ValidatorInterceptor.prototype, "logger", void 0); exports.ValidatorInterceptor = ValidatorInterceptor = tslib_1.__decorate([ (0, common_1.Injectable)() ], ValidatorInterceptor);