1.3.1 • Published 1 year ago

result-cache v1.3.1

Weekly downloads
-
License
-
Repository
github
Last release
1 year ago

Cache Promise Results

Cleanly cache the result of any function that returns a promise. API heavily inspired by @tanstack/query.

Zero dependencies (Redis optional)

npm install result-cache
import { createCache } from 'result-cache';

const { cache } = createCache({ ttl: 30 });

// If there's a previous value in the cache matching the key 'results', fetch and return it. 
// Otherwise, execute the fetch call and cache the result.
const result = await cache(() => fetch('api.example.com').then(response => response.json()), 'results');

Use with Redis

By default, records will be cached in memory (just a simple Map). This is only really advisable for development or testing. In production, configure the Redis driver:

npm install @redis/client
import { createCache } from 'result-cache';
import { RedisDriver } from 'result-cache/redis';

import { createClient } from '@redis/client';

const driver = new RedisDriver(createClient());
const { cache } = createCache({ driver });

Caveats

Serialisation

Objects will be serialised before being written to the cache. Therefore any unsupported attributes (functions, symbols) will be stripped when the cache is hit.

Validation

This library does not validate anything retrieved from the cache. This responsibility should lie outside the library. As such, it is strongly recommended to consider any data returned as unstructured.

import { z } from 'zod';

const personSchema = z.object({ name: z.string() });

const result = await cache(fetchPerson, 'person');

const person = personSchema.parse(result);
1.3.1

1 year ago

1.3.0

1 year ago

1.2.1

1 year ago

1.2.0

1 year ago

1.1.1

1 year ago

1.1.0

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago