1.0.0 • Published 7 months ago

@arsat/lock v1.0.0

Weekly downloads
-
License
ISC
Repository
github
Last release
7 months ago

Lock

Description

A decorator for methods in TypeScript that ensures that only one instance of the method can be executed at a time, using a mutex with a configurable timeout. This decorator uses the async-mutex library from npm.

Dependencies

This package relies on the async-mutex library from npm. Make sure it is installed in your project:

npm install async-mutex

Key Features:

Installation

You can install the Lock library using npm or yarn.

Using npm

npm install @arsat/lock

Using npm

yarn add @arsat/lock

Usage

Basic Example

Here's a basic example of how to use the Lock library to combine multiple classes:

import { Lock, ILockConfig } from "@arsat/lock";

const delay = (time: number) =>
  new Promise((resolve) => setTimeout(resolve, time));

class InUseError extends Error {
  constructor() {
    super("in use");
  }
}

class OneShot {
  private inUse = false;
  async run() {
    if (this.inUse) {
      throw new InUseError();
    } else {
      this.inUse = true;
      await delay(10);
    }
    this.inUse = false;
  }
}

const config: ILockConfig = {
  timeout: 50,
};

class OneShotLocked extends OneShot {
  @Lock({ timeout: 100 })
  async run() {
    return await super.run();
  }
}

const oneShot = new OneShot();
await Promise.all([oneShot.run(), oneShot.run(), oneShot.run()]); // throw error InUseError

const oneShotLocked = new OneShotLocked();
await Promise.all([oneShotLocked.run(), oneShotLocked.run()]); // not throw error

Configuration

The @Lock decorator accepts a configuration with the following options:

  • timeout: The maximum time (in milliseconds) that the decorator will wait to acquire the lock before throwing an error.
@Lock({ timeout: 100 })
async run() {
  // ...
}

Advanced Examples

Method with lock and wait

lass OneShotLockedEager extends OneShot {
  @Lock({ timeout: 100 })
  async run() {
    await delay(95);
    return await super.run();
  }
}

const oneShotLockedEager = new OneShotLockedEager();
await Promise.all([oneShotLockedEager.run(), oneShotLockedEager.run()]); // throw error E_TIMEOUT