JavaScript

Use LockDB with Node.js, Browser, Bun, or Deno.

Install

Node.js / Browser / Bun / Npm

You don't need to install anything with Deno, but here's how you do it with all others:

npm install --save-exact lockdb
yarn add --exact lockdb
pnpm add --save-exact lockdb

Usage

// import LockDB from 'lockdb';
// import LockDB from 'https://deno.land/x/lockdb@0.2.0/mod.ts';
const LockDB = require('lockdb');

const lockName = 'sales';
const locker = new LockDB('reports', { apiKey: 'api-key' });

// Check on a lock (optional)
const isReportLocked = await locker.check(lockName);
console.log(isReportLocked); // Outputs `false`

// Obtain a lock, waiting up to 30 seconds for it
try {
  await locker.lock(lockName);

  // Generate important/intensive report here

  // Unlock a lock, returning if it was locked before
  const wasReportLockedBeforeUnlock = await locker.unlock(lockName);
  console.log(wasReportLockedBeforeUnlock); // Outputs `true`
} catch (error) {
  console.error(`Failed to obtain lock (${lockName}): ${error}`);
}

// Obtain multiple locks, waiting up to 30 seconds for each
const anotherLockName = 'cleanup';
try {
  await locker.lock([lockName, anotherLockName]);

  // Generate important/intensive report cleanup here

  // Unlock all locks, returning if any was locked before
  const wasAnyLockedBeforeUnlock = await locker.unlock([lockName, anotherLockName]);
  console.log(wasAnyLockedBeforeUnlock); // Outputs `true`
} catch (error) {
  console.error(`Failed to obtain locks (${lockName}, ${anotherLockName}): ${error}`);
}

Options

Here are all the optional arguments in all methods.

// Initialization
const initOptions = {
  apiKey: 'some-api-key', // You can get yours from https://app.lockdb.com/settings
  serverUrl: 'https://api.lockdb.com', // You can change this if you want to implement your own backend. You can see the mock test server for a very basic implementation starting point at https://github.com/BrunoBernardino/lockdb/blob/main/mock_server.ts
};

const locker = new LockDB('reports', initOptions);

const lockName = 'sales';
const commonOptions = {
  waitTimeoutInMs: 5_000, // A number of milliseconds to wait for the method before "giving up" trying to reach the LockDB service (for lock, it defaults to 30_000)
};

// Locking
const lockOptions = {
  ...commonOptions,
  unlockWebhookUrl: 'https://example.com', // A URL which will receive a POST event (with `{ "serviceId": "<service id>", "lockName": "<lock name>" }` in the body) when the lock expires or is unlocked
  lockExpirationInSeconds: 300, // A number of seconds after which the lock will automatically expire
};

await locker.lock(lockName, lockOptions);

// Unlocking
const unlockOptions = {
  ...commonOptions,
};

await locker.unlock(lockName, lockOptions);

// Checking
const checkoptions = {
  ...commonOptions,
};

await locker.check(lockName, checkoptions);