UNPKG

@nestjs-redis/lock

Version:

Redis-based distributed lock module for NestJS, built on @redis-kit/lock

71 lines (70 loc) 3.14 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Redlock = Redlock; const common_1 = require("@nestjs/common"); const redlock_service_1 = require("./redlock.service"); // 7. Better TypeScript types function Redlock(key, ttl = 100) { return (target, propertyKey, descriptor) => { const keys = getKeys(key); // Guard against undefined descriptor if (!descriptor || typeof descriptor.value !== 'function') { throw new Error(`@Redlock can only be applied to methods. Property ${String(propertyKey)} is not a method.`); } (0, common_1.Inject)(redlock_service_1.RedlockService)(target, redlock_service_1.RedlockService.name); const originalMethod = descriptor.value; // Create wrapper method (always async since redlock operations are async) const wrappedMethod = async function (...args) { // eslint-disable-next-line @typescript-eslint/no-this-alias const that = this; // 9. Dependency injection edge case handling const redlockService = this[redlock_service_1.RedlockService.name]; if (!redlockService) { throw new Error(`RedlockService not found. Ensure the RedlockModule is imported in the same module as the class using @Redlock or isGlobal is true`); } return await redlockService.withLock(keys, ttl, () => originalMethod.apply(that, args)); }; // Metadata preservation // 1. Preserve the original method name Object.defineProperty(wrappedMethod, 'name', { value: originalMethod.name, configurable: true, }); // 2. Preserve the original method's parameter count (arity) Object.defineProperty(wrappedMethod, 'length', { value: originalMethod.length, configurable: true, }); // 3. Copy prototype properties if needed Object.setPrototypeOf(wrappedMethod, Object.getPrototypeOf(originalMethod)); // 4. Preserve custom properties const originalPropertyNames = Object.getOwnPropertyNames(originalMethod); for (const key of originalPropertyNames) { if (key !== 'name' && key !== 'length' && key !== 'prototype') { try { const descriptor = Object.getOwnPropertyDescriptor(originalMethod, key); if (descriptor) { Object.defineProperty(wrappedMethod, key, descriptor); } } catch (error) { // 5. Some properties might not be configurable, skip them console.warn(`Could not copy property ${key} from original method`); } } } descriptor.value = wrappedMethod; return descriptor; }; } function getKeys(key) { if (Array.isArray(key)) { return key; } else if (typeof key === 'string') { return [key]; } else { throw new Error(`Invalid key type: ${typeof key}. Expected string or string[].`); } }