UNPKG

nestjs-request-deduplication

Version:

[![npm version](https://badge.fury.io/js/nestjs-request-deduplication.svg)](https://www.npmjs.com/package/nestjs-request-deduplication) [![CI](https://github.com/daniyel/nestjs-request-deduplication/actions/workflows/pr-checks.yml/badge.svg)](https://gith

62 lines (61 loc) 2.9 kB
var RequestDeduplicationInterceptor_1; import { __awaiter, __decorate, __param } from "tslib"; import { Injectable, Inject, Logger, HttpException, HttpStatus } from '@nestjs/common'; import { from } from 'rxjs'; import { switchMap } from 'rxjs/operators'; import { RequestDeduplicationService } from '../services'; import * as crypto from 'crypto'; import { Reflector } from '@nestjs/core'; import { REQUEST_DEDUPLICATION_MODULE_OPTIONS, SKIP_DEDUPLICATE_REQUEST_KEY } from '../constants'; let RequestDeduplicationInterceptor = RequestDeduplicationInterceptor_1 = class RequestDeduplicationInterceptor { constructor(requestDeduplicationService, options, reflector) { this.requestDeduplicationService = requestDeduplicationService; this.options = options; this.reflector = reflector; this.logger = new Logger(RequestDeduplicationInterceptor_1.name); this.logger.log('RequestDeduplicationInterceptor initialized'); } intercept(context, next) { const skipDeduplicateRequest = this.reflector.get(SKIP_DEDUPLICATE_REQUEST_KEY, context.getHandler()); if (skipDeduplicateRequest) { return next.handle(); } const request = context.switchToHttp().getRequest(); const key = this.generateKey(request); const value = 'request_exists'; if (request.skipRequestDeduplication) { this.logger.log('Skipping request deduplication'); return next.handle(); } return from(this.requestDeduplicationService.processRequest(key, value, this.options.ttl)).pipe(switchMap((isProcessed) => { if (!isProcessed) { this.logger.log(`Duplicate request detected for key: ${key}`); throw new HttpException({ status: HttpStatus.CONFLICT, error: 'Duplicate request', }, HttpStatus.CONFLICT); } return next.handle().pipe(switchMap((data) => __awaiter(this, void 0, void 0, function* () { return data; }))); })); } generateKey(request) { var _a, _b; return (crypto .createHash('sha256') .update(request.method) .update(request.originalUrl) .update(JSON.stringify((_a = request.headers) !== null && _a !== void 0 ? _a : {})) // .update(JSON.stringify(request.query ?? {})) .update(JSON.stringify((_b = request.body) !== null && _b !== void 0 ? _b : {})) .digest('hex')); } }; RequestDeduplicationInterceptor = RequestDeduplicationInterceptor_1 = __decorate([ Injectable(), __param(0, Inject(RequestDeduplicationService)), __param(1, Inject(REQUEST_DEDUPLICATION_MODULE_OPTIONS)), __param(2, Inject(Reflector)) ], RequestDeduplicationInterceptor); export { RequestDeduplicationInterceptor };