nestjs-request-deduplication
Version:
[](https://www.npmjs.com/package/nestjs-request-deduplication) [](https://gith
73 lines (72 loc) • 2.93 kB
JavaScript
var RequestDeduplicationService_1;
import { __awaiter, __decorate, __param } from "tslib";
import { Injectable, Logger, Inject } from '@nestjs/common';
import { REQUEST_DEDUPLICATION_MODULE_OPTIONS } from '../constants';
import { MemcachedAdapter, MemoryAdapter, RedisAdapter } from '../storages';
let RequestDeduplicationService = RequestDeduplicationService_1 = class RequestDeduplicationService {
constructor(options) {
this.options = options;
this.logger = new Logger(RequestDeduplicationService_1.name);
}
onModuleInit() {
return __awaiter(this, void 0, void 0, function* () {
yield this.initStorage();
});
}
get storage() {
return RequestDeduplicationService_1.storageAdapter;
}
initStorage() {
return __awaiter(this, void 0, void 0, function* () {
if (RequestDeduplicationService_1.storageAdapter) {
return;
}
if (this.options.redisConfig) {
RequestDeduplicationService_1.storageAdapter = new RedisAdapter(this.options);
}
else if (this.options.memcachedConfig) {
RequestDeduplicationService_1.storageAdapter = new MemcachedAdapter(this.options);
}
else {
RequestDeduplicationService_1.storageAdapter = new MemoryAdapter(this.options);
}
yield RequestDeduplicationService_1.storageAdapter.init();
});
}
processRequest(key, value, ttl) {
return __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 __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}`);
}
});
}
};
RequestDeduplicationService = RequestDeduplicationService_1 = __decorate([
Injectable(),
__param(0, Inject(REQUEST_DEDUPLICATION_MODULE_OPTIONS))
], RequestDeduplicationService);
export { RequestDeduplicationService };