@mapbox/locking

4.0.0 • Public • Published

@mapbox/locking 🔒 Build Status

npm install --save @mapbox/locking

Wrap any callback or async function to use an LRU cache and prevent (lock) asynchronous operations across concurrent calls.

Usage

const { Locking, LockingAsync } = require('@mapbox/locking');

The options objects are passed directly to lru-cache allowing you to set the max age, max items, and other behaviors of the LRU cache. When options.allowStale is set to true the locking cache implements additional behavior to continue serving a stale item until the item has been refreshed in the background.

Locking(function, options)

For locking callback functions in the form function(id, callback). Returns a callable function

const { Locking } = require('@mapbox/locking');
const fs = require('fs');
const readFile = Locking(fs.readFile, options);

// Reads file once, calls callback 10x.
for (let i = 0; i < 10; i++) {
  readFile('./sample.txt', function(err, data) {
    console.log(data);
  });
}

LockingAsync(function, options)

Constructor for locking promise or async functions in the form of function(...arguments). This can manage functions of arbitrary arguments and types. Returns a class with two functions, which includes a callable method get() for calling the original function.

const { LockingAsync } = require('@mapbox/locking');
const got = require('got');

const jsonApi = new Locking((url) => {
  return got(url).json();
}, options);

// call function
await jsonApi.get('https://api.mapbox.com');
await jsonApi.get('https://api.mapbox.com');
await jsonApi.get('https://api.mapbox.com');

// get stats
console.log(jsonApi.stats); // { total: 3, hit: 2, miss: 1, locks: 2, refreshHit: 0, currentLocks: 0, size: 1 }

/@mapbox/locking/

    Package Sidebar

    Install

    npm i @mapbox/locking

    Weekly Downloads

    1,029

    Version

    4.0.0

    License

    none

    Unpacked Size

    22.2 kB

    Total Files

    10

    Last publish

    Collaborators

    • mbx-npm-ci-production
    • mbx-npm-ci-staging
    • mbx-npm-advanced-actions-production
    • mbx-npm-advanced-actions-staging
    • mbx-npm-09-production
    • mbx-npm-08-production
    • mbx-npm-07-production
    • mbx-npm-06-production
    • mbx-npm-05-production
    • mbx-npm-04-production
    • mbx-npm-03-production
    • mbx-npm-02-production
    • mbx-npm-01-production
    • mbx-npm-02-staging
    • mapbox-npm-01
    • mapbox-npm-02
    • mapbox-npm-07
    • mapbox-npm-03
    • mapbox-npm-04
    • mapbox-npm-09
    • mapbox-npm-05
    • mapbox-npm-06
    • mapbox-npm-08
    • mapbox-npm-advanced-actions
    • mapbox-npm-ci
    • mapbox-npm
    • mapbox-admin
    • mapbox-machine-user