Last active
September 27, 2022 21:34
-
-
Save saikatdutta1991/f90e04d6416d89534e3802681cb114f6 to your computer and use it in GitHub Desktop.
NestJS: Clean Code With Decorators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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