Giter VIP home page Giter VIP logo

request-redis-cache's Introduction

request-redis-cache Build status

Fault tolerant pass-through cache for generic requests backed by Redis

We attempt to serve data cached by Redis. If that data is not found, we fetch it from the server via an externally provided function and cache its response.

If Redis is down or misbehaving, errors are emitted but we continue to interact with the uncached function as if we were talking to the service directly.

This was built along side backbone-api-client to make transparently caching responses from API clients easier.

Getting Started

Install the module with: npm install request-redis-cache

// Generate a new cache
var redis = require('redis');
var RequestRedisCache = require('request-redis-cache');
var redisClient = redis.createClient();
var cache = new RequestRedisCache({
  redis: redisClient
});

// Fetch some data from a fake client
cache.get({
  cacheKey: 'hello-world',
  cacheTtl: 100, // seconds
  // Dynamic `options` to pass to our `uncachedGet` call
  requestOptions: {},
  // Action to use when we cannot retrieve data from cache
  uncachedGet: function (options, cb) {
    // Simulate data coming back from an API client (should be already parsed)
    cb(null, {hello: 'world'});
  }
}, function handleData (err, data) {
  // Look at the data in our cache, '{"hello":"world"}'
  redisClient.get('hello-world', console.log);

  // Re-retrieve the data
  cache.get({
    cacheKey: 'hello-world',
    cacheTtl: 100,
    requestOptions: {},
    uncachedGet: function (options, cb) {
      cb(new Error('This will not be reached since the data is cached'));
    }
  }, console.log); // {hello: 'world'}
});

Documentation

request-redis-cache exports the constructor RequestRedisCache as its module.exports.

RequestRedisCache(options)

Constructor for a new cache. RequestRedisCache extends from an EventEmitter and invokes its constructor during the instantiation process.

  • params Object, container for parameters
    • redis Redis, instance of redis to cache via
    • stringify Function, optional serializer for when saving data to Redis
      • By default, this is JSON.stringify
      • stringify will receive data from uncachedGet and is expected to return a String
    • parse Function, optional deserializer for restoring data from Redis
      • By default, this is JSON.parse
      • parse will receive a String and is expected to restore via same format that uncachedGet would callback with

cache#get(params, cb)

Method to retrieve data from Redis or a server depending of it has been cached/not.

If there are any errors while interacting with Redis, then they will be emitted via error channel. If these are handled (via .on/.once), then get will still function by talking to the server.

  • params Object, container for parameters
    • cacheKey String, key to retrieve/save data under
    • cacheTtl Number, seconds to cache information for
    • requestOptions Mixed, parameters to be used in uncachedGet
    • uncachedGet Function, (options, cb) function to resolve external data
      • options Mixed, data passed in via requestOptions
      • cb Function, error-first function, (err, data), to callback with data
        • err Error|null, error if any occurred during retrieval
        • data Mixed, data retrieved from external call
      • We choose this split structure of requestOptions/uncachedGet because it is expected that uncachedGet remains generic while requestOptions can shift from case to case
  • cb Function, error-first callback, (err, data), to receive fetched data
    • err Error|null, error if any occurred during retrieval
    • data Mixed, data retrieved from cache/external call
Emitted errors

Errors that are emitted will originally come from redis or params.parse. To be nice, we add on a few extra data points

  • action String, human explanation of what went wrong
  • cacheKey String, key we were using with Redis
  • cacheTtl Number, TTL we were using with Redis
  • info Mixed, value we retrieved fia uncachedGet
    • This can only be found when params.stringify cannot stringify the data
  • infoStr String, stringified form of data from uncachedGet/Redis
    • This can only be found when we are interacting with to be cached or already cached data

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint via grunt and test via npm test.

License

Copyright (c) 2014 Uber Technologies, Inc.

Licensed under the MIT license.

request-redis-cache's People

Contributors

twolfson avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

request-redis-cache's Issues

Move off of `errs` as error extension engine

Due to node_redis' internals we must clone errors instead of writing new properties to them.

https://github.com/mranney/node_redis/blob/master/index.js#L139-L142

During our short search, we could only find errs which supports cloning/extending of errors via its merge method. However, errs does a little too much for my taste (e.g. adds toJSON to prototype, adds excess stacktrace/description properties).

https://github.com/flatiron/errs#merging-with-existing-errors

Prevent cache stampedes

In order to prevent flooding external resources when we are fetching uncached data, introduce an aggregation mechanism for using a joint callback.

Taken from: https://github.com/errorception/redis-memoizer

I am a bit uncertain if this will introduce unwanted complexity/not but for now I am giving it the benefit of the doubt.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.