1.0.3 • Published 8 months ago

@figmarine/cache v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

:notebook_with_decorative_cover: Table of Contents

:star2: Package Details

A Node.js library for caching arbitrary data to disk and restoring cache in between runs. Used by figmarine to cache REST API return values.

  • Disk-based memory store
  • Configurable store location
  • Configurable TTL, cache size and refresh rate
  • Allows you to wrap functions for automatic caching

:eyes: Usage

Install the package with the following command:

 pnpm i @figmarine/cache

Then, import makeCache and call it:

import { makeCache, type MakeCacheOptions } from '@figmarine/cache';

const { cache, shutdownGracefully } = makeCache({
  // A relative path creates a subfolder in /tmp/@figmarine/cache.
  location: 'rest',
  // Pass -1 to push the TTL to its limit (one year TTL).
  ttl: -1,
});

You can use the disk cache directly if you want to write into it and handle it manually.

await cache.set('myKey', 'My value');

const value = await cache.get<string>('myKey');
console.log(value); // 'My value'

await cache.delete(key);
const value = await cache.get<string>('myKey');
console.log(value); // 'undefined'

You can also wrap existing functions with .getCache().wrap(). When a wrapped function is called, its return value is cached using the function parameters as a cache key. On the second call with the same parameters, the cached value will be returned instantly and the function body won't need to be called ( provided the cached content hasn't expired).

const queryFoo = (key) => axios.get(`/foo?ID=${key}`);
const cachedQueryFoo = cache.getCache().wrap(queryFoo, { key: 'uniqueKeyForThisFunction' });

console.time('First call');
const first = cachedQueryFoo('1234');
console.timeEnd('First call');
// First call: 1081.284912109375 ms

console.time('Second call');
const second = cachedQueryFoo('1234');
console.timeEnd('Second call');
// Second call: 0.108056640625 ms

:running: Run Locally

Clone the project

  git clone https://github.com/Sidnioulz/figmarine.git

Go to the project directory

  cd packages/cache

Install dependencies

  pnpm install

Build the code as you make changes

  pnpm dev

Check that tests run as you make changes

  pnpm test:dev

:wave: Contributing

See how to contribute.

:warning: License

Distributed under the MIT License.

:sos: Support

Please open a conversation in the discussion space to ask a question.

Please open an issue for bug reports or code suggestions.

:yellow_heart: Acknowledgments

1.0.3

8 months ago

1.0.2

8 months ago

1.0.1

8 months ago

1.0.0

8 months ago