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

76 lines (75 loc) 3.15 kB
"use strict"; var RequestDeduplicationService_1; Object.defineProperty(exports, "__esModule", { value: true }); exports.RequestDeduplicationService = void 0; const tslib_1 = require("tslib"); const common_1 = require("@nestjs/common"); const constants_1 = require("../constants"); const storages_1 = require("../storages"); let RequestDeduplicationService = RequestDeduplicationService_1 = class RequestDeduplicationService { constructor(options) { this.options = options; this.logger = new common_1.Logger(RequestDeduplicationService_1.name); } onModuleInit() { return tslib_1.__awaiter(this, void 0, void 0, function* () { yield this.initStorage(); }); } get storage() { return RequestDeduplicationService_1.storageAdapter; } initStorage() { return tslib_1.__awaiter(this, void 0, void 0, function* () { if (RequestDeduplicationService_1.storageAdapter) { return; } if (this.options.redisConfig) { RequestDeduplicationService_1.storageAdapter = new storages_1.RedisAdapter(this.options); } else if (this.options.memcachedConfig) { RequestDeduplicationService_1.storageAdapter = new storages_1.MemcachedAdapter(this.options); } else { RequestDeduplicationService_1.storageAdapter = new storages_1.MemoryAdapter(this.options); } yield RequestDeduplicationService_1.storageAdapter.init(); }); } processRequest(key, value, ttl) { return tslib_1.__awaiter(this, void 0, void 0, function* () { try { const existingValue = yield this.storage.get(key); if (existingValue) { this.logger.log(`Request for ${key} already processed.`); return false; } this.logger.log(`Request for ${key} not yet processed.`); this.logger.log(`Request for ${key} processing.`); yield this.storage.set(key, value, ttl); this.logger.log(`Request for ${key} processed.`); return true; } catch (error) { this.logger.error(`Error processing request for ${key}: ${error.message}`); throw error; } }); } deleteRequest(key) { return tslib_1.__awaiter(this, void 0, void 0, function* () { try { yield this.storage.delete(key); this.logger.log(`Request for ${key} deleted.`); } catch (error) { this.logger.error(`Error deleting request for ${key}: ${error.message}`); } }); } }; exports.RequestDeduplicationService = RequestDeduplicationService; exports.RequestDeduplicationService = RequestDeduplicationService = RequestDeduplicationService_1 = tslib_1.__decorate([ (0, common_1.Injectable)(), tslib_1.__param(0, (0, common_1.Inject)(constants_1.REQUEST_DEDUPLICATION_MODULE_OPTIONS)) ], RequestDeduplicationService);