fix: fix bugs and structure
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { REDIS } from '../constants/redis.constants';
|
||||
import Redis from 'ioredis';
|
||||
import { randomUUID } from 'crypto';
|
||||
|
||||
@Injectable()
|
||||
export class RedisService {
|
||||
@@ -38,6 +39,22 @@ export class RedisService {
|
||||
return await this.redis.del(key);
|
||||
}
|
||||
|
||||
async acquireLock(key: string, ttlSeconds = 5): Promise<string | null> {
|
||||
const token = randomUUID();
|
||||
|
||||
const result = await this.redis.set(key, token, 'EX', ttlSeconds, 'NX');
|
||||
|
||||
return result === 'OK' ? token : null;
|
||||
}
|
||||
|
||||
async releaseLock(key: string, token: string): Promise<void> {
|
||||
const value = await this.redis.get(key);
|
||||
|
||||
if (value === token) {
|
||||
await this.redis.del(key);
|
||||
}
|
||||
}
|
||||
|
||||
async onModuleDestroy() {
|
||||
await this.redis.quit();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user