with-simple-caching

A wrapper that makes it simple to add caching to any function

Usage no npm install needed!

<script type="module">
  import withSimpleCaching from 'https://cdn.skypack.dev/with-simple-caching';
</script>

README

with-simple-caching

ci_on_commit deploy_on_tag

A wrapper that makes it simple to add caching to any function.

Notable features:

  • Wrapper pattern for simple and clean usage
  • Automatic cache key definition
  • Customizable cache data store

Install

npm install --save with-simple-caching

Examples

Add caching to an existing function

import { createCache } from 'simple-in-memory-cache';
import { withSimpleCaching } from 'with-simple-caching';

const getRecipesFromApiWithCaching = withSimpleCaching(getRecipesFromApi, { cache: createCache() });

Define the function with caching directly

import { createCache } from 'simple-in-memory-cache';
import { withSimpleCaching } from 'with-simple-caching';

const getBookByName = withSimpleCaching(
  async (name: string) => {
    /* ... get the book ... */
    return book;
  },
  {
    cache: createCache(),
  },
);

Use a custom persistance layer

local storage, for example:

import { withSimpleCaching } from 'with-simple-caching';

const getRecipesFromApiWithLocalStorageCaching = withSimpleCaching(getRecipesFromApi, {
  // just define how a cache can `get` from and `set` to this data store
  cache: {
    get: (key) => localStorage.getItem(key),
    set: (key, value) => localStorage.setItem(key, value),
  },
});

Features

Automatic cache key

The arguments your function is invoked with is used as the cache key, after serialization. For example:

import { createCache } from 'simple-in-memory-cache';
import { withSimpleCaching } from 'with-simple-caching';

const getZodiacSign = withSimpleCaching(async ({ birthday }: { birthday: string }) => /* ... */, { cache: createCache() });

getZodiacSign({ birthday: '2020-07-21' }); // here the cache key is `[{"birthday":"2020-07-21"}]`

note: array order does matter

Customizable cache data store

You can easily use a custom cache or custom data store / persistance layer for caching with this wrapper.

import { withSimpleCaching } from 'with-simple-caching';

const getZodiacSign = withSimpleCaching(
  async ({ birthday }: { birthday: string }) => /* ... */,
  {
    cache: {
      get: (key: string) => /* ... how to get from your custom data store ... */,
      set: (key: string, value: any) => /** ... how to set to your custom data store ... */,
    }
  }
);