All Projects → PatrickJS → Redis Dataloader

PatrickJS / Redis Dataloader

Licence: mit
Batching and Caching layer using Redis as the Caching layer

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Redis Dataloader

dataloader
Dataloader is a generic utility for batch data loading with caching, works great with GraphQL
Stars: ✭ 114 (+58.33%)
Mutual labels:  promise, dataloader
Socket.io Rpc
Extend your promises across a network with socket.io
Stars: ✭ 67 (-6.94%)
Mutual labels:  promise
Before After Hook
wrap methods with before/after hooks
Stars: ✭ 49 (-31.94%)
Mutual labels:  promise
Yux Storage
yux-storage 是一个基于 HTML5 IndexedDB 封装的 Web 本地数据离线存储库
Stars: ✭ 64 (-11.11%)
Mutual labels:  promise
Gollback
Go asynchronous simple function utilities, for managing execution of closures and callbacks
Stars: ✭ 55 (-23.61%)
Mutual labels:  promise
Promised Pipe
A ramda.pipe-like utility that handles promises internally with zero dependencies
Stars: ✭ 64 (-11.11%)
Mutual labels:  promise
Emacs Async Await
Async/Await for Emacs
Stars: ✭ 47 (-34.72%)
Mutual labels:  promise
Http Vue Loader
load .vue files from your html/js
Stars: ✭ 1,172 (+1527.78%)
Mutual labels:  promise
Emittery
Simple and modern async event emitter
Stars: ✭ 1,146 (+1491.67%)
Mutual labels:  promise
Composepictures
This is a project built using Jetpack Compose on UI, Clean architecture, Dagger Hilt, Kotlin Flow, Navigation Components etc.
Stars: ✭ 62 (-13.89%)
Mutual labels:  datastore
Sleep Promise
Resolves a promise after a specified delay.
Stars: ✭ 60 (-16.67%)
Mutual labels:  promise
Ws Wrapper
Lightweight WebSocket lib with socket.io-like event handling, requests, and channels
Stars: ✭ 58 (-19.44%)
Mutual labels:  promise
Flowa
🔥Service level control flow for Node.js
Stars: ✭ 66 (-8.33%)
Mutual labels:  promise
Download
Download and extract files
Stars: ✭ 1,064 (+1377.78%)
Mutual labels:  promise
Write
Write data to the file system, creating any intermediate directories if they don't already exist. Used by flat-cache and many others!
Stars: ✭ 68 (-5.56%)
Mutual labels:  promise
Fs Readfile Promise
Promisified version of fs.readFile
Stars: ✭ 48 (-33.33%)
Mutual labels:  promise
Goshare
Go Share your TimeSeries/NameSpace/KeyVal DataStore (using leveldb) over HTTP &/or ZeroMQ
Stars: ✭ 59 (-18.06%)
Mutual labels:  datastore
Callbag Map Promise
Callbag map promise
Stars: ✭ 64 (-11.11%)
Mutual labels:  promise
Cofx
A node and javascript library that helps developers describe side-effects as data in a declarative, flexible API.
Stars: ✭ 72 (+0%)
Mutual labels:  promise
Graphql Batch
A query batching executor for the graphql gem
Stars: ✭ 1,164 (+1516.67%)
Mutual labels:  promise

Redis Dataloader

Batching and Caching layer using Redis as the Caching layer. Redis Dataloader wraps Facebook Dataloader, adding Redis as a caching layer.

npm install redis-dataloader
or
yarn add redis-dataloader

Example

const redisClient = require('redis').createClient();
// the "ioredis" module is also supported
// const Redis = require('ioredis');
// const redisClient = new Redis();
const DataLoader = require('dataloader');
const RedisDataLoader = require('redis-dataloader')({ redis: redisClient });

const loader = new RedisDataLoader(
    // set a prefix for the keys stored in redis. This way you can avoid key
    // collisions for different data-sets in your redis instance.
    'redis-key-prefix',
    // create a regular dataloader. This should always be set with caching disabled.
    new DataLoader(myBatchLoadFunction, { cache: false }),
    // The options here are the same as the regular dataloader options, with
    // the additional option "expire"
    {
        // caching here is a local in memory cache. Caching is always done
        // to redis.
        cache: true,
        // if set redis keys will be set to expire after this many seconds
        // this may be useful as a fallback for a redis cache.
        expire: 60,
        // can include a custom serialization and deserialization for
        // storage in redis.
        serialize: date => date.getTime(),
        deserialize: timestamp => new Date(timestamp)
    }
);

// load an individual item by its key
loader.load(5).then(resp => console.log(resp));

//clear an individiaul item from the local and redis cache.
loader.clear(5).then(() => {})

API Documentation

In general, RedisDataLoader has the same API as the Facebook Dataloader Api, with a few differences. Read through the Facebook Dataloader documentation and then note the differences mentioned here.

  • clear returns a promise (waits until redis succeeds at deleting the key). Facebook Dataloader's clear method is synchronous.
  • clearAll is not available (redis does not have an efficient way to do this?)
  • prime will always overwrite the cache. Facebook Dataloader will only write to its cache if a value is not already present. Prime is asyncronous and returns a Promise.
  • dataloader results must be either null or a JSON object.
  • two functions: clearLocal(key) and clearAllLocal() allow you to clear the local cache only.

Instantiation

Dependency inject a Redis Connection

const redis = require('redis').createClient();
const RedisDataLoader = require('redis-dataloader')({ redis: redis });

Create a new Dataloader.

Each Dataloader holds its own local in memory cache (Same as Facebook Dataloader), and additionally caches to your Redis instance.

const loader = new RedisDataLoader('<redis key prefix>', '<Facebook Dataloader>', '<Options>');
Redis Key Prefix

Specify a Prefix that will be appended to each key when storing in Redis.

So for example if your prefix is "bar" and you call loader.load('foo'), this key will be stored in Redis as bar:foo

Facebook Dataloader

A regular Facebook Dataloader is passed in as the second parameter. It will be used to fetch data from your underlying datastore (mongo, sql, whatever). It is very important to disable the cache on this dataloader. Redis dataloader will already do local in memory caching (unless you disable it).

Options

All the options available to Facebook Dataloader can be passed in here. An additional option called expire is also available, and will set a ttl in seconds on all keys set in redis if this option is passed.

The cacheKeyFn will default to serialize objects and arrays using json-stable-stringify and allow all other values to pass through unchanged.

Caching

The purpose of Redis Dataloader is to provide a caching layer in redis on top of the Facebook Dataloader. Facebook's Dataloader provides a local in memory cache. This may be ok for short lived per-request caches, but may not be sufficient if you need a long lived cache and/or you have multiple webservers that need to share data.

Redis Dataloader will additionally use the same local cache that Facebook Dataloader provides. It will first check the local cache, then check the redis cache, before finally checking your underlying datastore. This pattern may be desirable if for example you create a new DataLoader for each request. If your dataloader is long-lived you may want to disable to the local cache, and just rely on the redis cache instead

const loader = new RedisDataLoader('prefix', new DataLoader(), { cache: false });

Development

  1. Install Dependencies npm install
  2. Start Redis docker-compose stop && docker-compose rm && docker-compose build && docker-compose up -d
  3. Run Tests npm test
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].