@remembered/redis-semaphore
TypeScript icon, indicating that this package has built-in type declarations

0.2.2 • Public • Published

Actions Status Actions Status Actions Status Test Coverage Maintainability Packages npm version

Remembered redis semaphore implementation, to be used with @remembered/redis This packages uses redis-semaphore under the hood.

How to Install

npm i @remembered/redis-semaphore

How to use it

When instantiating RememberedRedis, just inform an instance os RememberedRedisSemaphore

const semaphore = new RememberedRedisSemaphore(IORedisInstanceForSemaphore, {

})

const remembered = new RememberedRedis({
  ttl: 200, // In milliseconds
  redisTtl: 10000 // In seconds
  semaphore,
}, IORedisInstance);

Although this package is meant to use as a plugin for RememberedRedis, you can also use it as a completely standalone one.

It offers three different approaches to use semaphores.

The first and most basic one is through acquiring and releasing it manually, like this:

  const release = await semaphore.acquire('my semaphore id');
  try {
    // Put here anything you want to do
  } finally {
    await release();
  }

It's always recommended to put the release call into a finally statement, to guarantee it was released. You can also use the callback approach, where it is executed within the semaphore, like this:

const result = await semaphore.run('my semaphroe id', () => {
  // Put here anything you want to do
});

result here will be the result of the informed callback. Finally, the last possible approach is to wrap a function, making a version of it that do the same job, but within a semaphore. Like this:

const wrapped = semaphore.wrap((arg1, arg2, arg3) => {
  // Put here anything you want to do
}, (arg1, arg2, arg3) => {
  // Put here the algorithm to select the key based on the callback parameters
});


const result = await wrapped(value1, value2, value3);

See that, the first callback is the one that will be executed within a semaphore, while the second one must return the key to be used in the semaphore. The second callback will received the exact same parameters of the first one. You can use wrapped to replace instance methods for versions wrapped in a semaphore, or to create functions that will be passed as a callback to other ones, that will use a semaphore.

License

Licensed under MIT.

Package Sidebar

Install

npm i @remembered/redis-semaphore

Weekly Downloads

8

Version

0.2.2

License

MIT

Unpacked Size

13.4 kB

Total Files

13

Last publish

Collaborators

  • farenheith
  • danielgaleni