@s1seven/nestjs-tools-lock
TypeScript icon, indicating that this package has built-in type declarations

0.7.0 • Public • Published

Lock

npm

The Lock Service produce distributed locks to prevent duplicated/conflicted actions to be executed in a distributed environment. It is based on Redlock module.

Installation

$ npm install --save @s1seven/nestjs-tools-lock

Usage

Inside a CronJob service

import { LockService } from '@s1seven/nestjs-tools-lock';
import { Inject, Injectable } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';

@Injectable()
export class TasksService implements OnModuleDestroy {
  constructor(@Inject(LockService) private lockService: LockService) {}

  onModuleDestroy() {
    this.lockService.close();
  }

  // using returned unlock function
  @Cron('*/10 * * * * *')
  async doThis(): Promise<void> {
    const lockKey = 'doThis';
    const { unlock } = await this.lockService.lock(lockKey, 2000);
    if (typeof unlock !== 'function') {
      return;
    }
    unlock();
  }

  // using lock id
  @Cron('*/10 * * * * *')
  async doThat(): Promise<void> {
    const lockKey = 'doThat';
    await this.lockService.optimist(lockKey, 2000);
    const { lockId } = await this.lockService.lock(lockKey, 2000);
    this.lockService.unlock(lockKey, lockId);
  }
}

Readme

Keywords

none

Package Sidebar

Install

npm i @s1seven/nestjs-tools-lock

Weekly Downloads

4

Version

0.7.0

License

ISC

Unpacked Size

122 kB

Total Files

16

Last publish

Collaborators

  • christophbuehler
  • eamon0989
  • s1seven-service
  • stiebitzhofer