Tiny library that caches the result of any function that returns a promise. API heavily inspired by @tanstack/query.
Fully typed; zero dependencies (Redis optional)
npm install result-cacheimport{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.constresult=awaitcache(()=>fetch('api.example.com').then(response=>response.json()),'results');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/clientimport{createCache}from'result-cache';import{RedisDriver}from'result-cache/redis';import{createClient}from'@redis/client';constdriver=newRedisDriver(createClient());const{ cache }=createCache({ driver });Objects will be serialised before being written to the cache. Therefore any unsupported attributes (functions, symbols) will be stripped when the cache is hit.
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';constpersonSchema=z.object({name: z.string()});constresult=awaitcache(fetchPerson,'person');constperson=personSchema.parse(result);