Skip to content

Instantly share code, notes, and snippets.

@saikatdutta1991
Last active September 27, 2022 21:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saikatdutta1991/f90e04d6416d89534e3802681cb114f6 to your computer and use it in GitHub Desktop.
Save saikatdutta1991/f90e04d6416d89534e3802681cb114f6 to your computer and use it in GitHub Desktop.
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