9.0.0 • Published 12 months ago

@edirect/lock v9.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
12 months ago

@edirect/lock

The EDirectInsure Distributed Lock module.

Installation

$ npm i --save @edirect/lock

Usage

Import and register LockModule on AppModule (app.module.ts):

import { ConfigService } from '@edirect/config';

...

imports: [

  LockModule.registerAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        lockOwner: configService.get(Variables.NAMESPACE),
        redis: {
          host: configService.get(Variables.REDIS_HOST),
          password: configService.get(Variables.REDIS_PASS),
          port: +configService.get(Variables.REDIS_PORT),
        },
      }),
      inject: [ConfigService],
    }),

  ...
]

Use the public methods in the code, where applicable:

/**
 * Timed Lock
 */
public lock(key: string, callback: (unlock: () => void) => void, ttl?: number): void

/**
 * Redis Values
 */
public set(key: string, value: string, override = false): Promise<void>
public get(key: string): Promise<string>
public del(key: string): Promise<void>

/**
 * Distributed Lock
 */
public async getLockOwner(): Promise<string>
public async setLockOwner(): Promise<string>
public async removeLockOwner(): Promise<void>
public async isLockOwner(): Promise<boolean>

For example, the usage of the Distributed Lock:

if (await this.lockService.isLockOwner()) {

  // Logic that should run on only one cluster

}

And for the Timed Lock:

this.lockService.lock('locked-task-name', async (unlock) => {

  // Logic that should be executed in exclusivity, across all instances

  unlock();
});