Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NestJS: Clean Code With Decorators
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CustomLogger } from 'src/common/decorators/custom-logger.decorator';
import { Redis } from '../redis/redis';
import { LockAcquireException } from './exceptions/lock-acquire.exception';
@Injectable()
export class LockService {
@CustomLogger()
private readonly logger: Logger;
constructor(@Inject(Redis.REDIS) private readonly redis: Redis) {}
public async acquireLock(options: {
key: string;
releaseAfterSeconds?: number;
}): Promise<void> {
const lock = await this.redis.set(
options.key,
'true',
'EX',
options.releaseAfterSeconds,
'NX',
);
if (lock !== 'OK') {
throw new LockAcquireException(
`Failed to acquire lock on ${options.key}`,
);
}
this.logger.log(`Lock acquired on key ${options.key}`);
}
public async releaseLock(key: string): Promise<void> {
await this.redis.del([key]);
this.logger.log(`Lock released from key ${key}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment