@comparaonline/idempotence-lib

Contains utilities to manage idempotence executions

Usage no npm install needed!

<script type="module">
  import comparaonlineIdempotenceLib from 'https://cdn.skypack.dev/@comparaonline/idempotence-lib';
</script>

README

SetUp

Initialize redis with the provided utility

import { RedisConfig } from '@comparaonline/idempotence-lib/redis-config';
import { initializeIdempotenceRedis } from '@comparaonline/idempotence-lib/initialize-idempotence-redis';

const config: RedisConfig = {
  host: 'localhost'
};

initializeIdempotenceRedis(config);

Usage

executeWithStringKey

Signature:

executeWithStringKey<T = any>(key: string, fn: () => T, expireTime: number): Promise<T | undefined>
Param Type Description
key string The key to use to verify uniqueness.
fn function The function to execute in case us the first time the key is used.
expireTime number The expiration time in seconds to keep the result asociated to the key. By default is 10 days.

The result will be undefined if the function is called again with the same key and it didn't obtain the result for the first call yet.

Use example:

import { IdempotenceManager } from '@comparaonline/idempotence-lib/idempotence-manager';

const myFn = async (event: any) => {
  const result = IdempotenceManager.executeWithStringKey(event.id, () => {
    // process Event
    return Math.random();
  });
  console.log(result);
};

executeWithObjectKey

Signature:

executeWithObjectKey<T = any>(objToHash: any, fn: () => T, expireTime: number): Promise<T | undefined>
Param Type Description
objToHash any The object that will be hashed to a unique key.
fn function The function to execute in case us the first time the key is used.
expireTime number The expiration time in seconds to keep the result asociated to the key. By default is 10 days.

The result will be undefined if the function is called again with the same key and it didn't obtain the result for the first call yet.

Use example:

import { IdempotenceManager } from '@comparaonline/idempotence-lib/idempotence-manager';

const myFn = async (event: any) => {
  const result = IdempotenceManager.executeWithObjectKey(event, () => {
    // process Event
    return Math.random();
  });
  console.log(result);
};