output-cache

A Node JS module to help with caching HTTP responses

npm install output-cache
7 downloads in the last week
14 downloads in the last month

output-cache

Output-cache is a NodeJS module that can be used to cache HTTP responses in memory on the server.

  • Perfect for caching your RESTful endpoints
  • Similar functionality to .NET OutputCache attribute
  • Configurable and easy to invalidate entries in the cache
  • 100% unit test coverage

Build Status

Installation

npm install output-cache

Usage

Disclaimer: The output-cache module defines a cache on a per-route basis, and therefore, you'll most likely need to have some sort of routing framework in place. The caching needs to happen after routing. I recommend using this in conjunction with a module like express or restify.

You can create a new output cache instance like so:

var OutputCache = require('output-cache');
var outputCache = new OutputCache(options);

The constructor takes an options object that can have the following properties:

  • maxCacheSizePerRoute (default: 50) - The maximum number of items to keep in the cache on a per route basis
  • removeOldEntriesWhenFull (default: false) - If set to true and the cache is full, it will always keep the newest entries and automatically remove the oldest ones
  • parametersPropertyName (default: 'params') - Modules like express and restify assign route paramters to a 'params' property on the request object. If you are using a module that stores route parameters on a different named property on the request object, use this to configure where parameters are stored.
  • headersPropertyName (default: 'headers') - Modules like express and restify assign request header values to a 'headers' property on the request object. If you are using a module that stores request header values on a different named property on the request object, use this to configure where request header values are stored.

Note: these are also available as public properties.

The get method is used to define the route and options for caching the response to a given endpoint:

get(server:Object, route:String, options:Object, routeHandler:Function)
  • server - required, the http server that handles requests (this object should provide a "get" method, and is recommended that you use a framework like express or restify)
  • route - required, the route that the cached response will be associated to
  • options - optional, the options to use for caching; see below for more deatils
  • routeHandler - required, the logic that will be run when there is nothing in the cache for the request (your normal route handling logic)
  • returns a handle to a function that is used to intercept the sending of responses (you really don't need to care much about this :))

Caching Options:

  • location (default: 'none') - tells the server what cache control headers should be sent along with the response and if responses should be cached on the server. Valid locations are:
    • 'none' - Not cached on server, Cache-Control: none
    • 'server - Cached on server, Cache-Control: none
    • 'downstream' - Not cached on server, Cache-Control: public
    • 'any' - Cached on server, Cache-Control: public
    • 'client' - Not cached on server, Cache-Control: private
    • 'serverAndClient' - Cached on server, Cache-Control: private
  • varyByParam (default: []) - a collection of the names of parameters to vary the cache on (case sensitive)
  • varyByHeader (default: []) - a collections of the names of headers to vary the cache on (case insensitive)
  • durationSeconds (default: 1) - the number of seconds to cache the response
  • useSlidingExpiration (default: false) - tells the module whether or not the entry's cache duration will be reset on a cache hit
  • headersToCache (default: []) - a collection of names of headers to cache log with the response body (case insensitive, i.e. 'content-type')

The invalidate method is used to remove entries from the cache:

invalidate(route:String, parameters:Object, headers:Object)
  • route - required, the route that the cached response will be associated to
  • parameters - required, an object containing the names and values of the parameters of the request to invalidate
  • headers - required, an object containing the names and values of the headers of the request to invalidate

How it works

Instead of defining the route handler on your app/server object, you'll want to define it on the outputCache instance. Inside the handler for the given route, an object named cachedResponse may be available on the request object. If it is, that means it was previously cached and can be used to respond to the request right away. The following properties are available on the cachedResponse object:

  • status - the status code of the previously cached response
  • headers - the response headers (only the ones defined within the caching options by 'headersToCache') of the previously cached response
  • reason - the custom reason of the previously cached response (can be undefined)
  • responseBody - the response body of the previously cached response (can be undefined)
  • encoding - the encoding of the response body of the previously cached response (can be undefined)

Here is a simple example:

var app = require('express').createServer(),
    OutputCache = require('output-cache'),
    outputCache = new OutputCache({ maxCacheSizePerRoute: 10, removeOldEntriesWhenFull: true}),
    cacheOptions = {
        location: outputCache.cacheLocation.SERVER,
        varyByParam: ['userId'],
        durationSeconds: 60,
        headersToCache: ['Content-Type', 'content-length']
    };

outputCache.get(app, '/users/:userId', cacheOptions, function(req, res, next) {
    if (req.cachedResponse) {
        // iterate through all the cached response headers, and set them
        for (var prop in req.cachedResponse.headers) {
            if (req.cachedResponse.headers.hasOwnProperty(prop)) {
                res.setHeader(prop, req.cachedResponse.headers[prop]);
            }
        }
        res.send(req.cachedResponse.status, req.cachedResponse.responseBody);
    }
    else {
        if (req.params.userId < 1) {
            res.send(404, 'Not Found');
            return;
        }
        res.send(200, 'hello user:' + req.params.userId);
    }
}));

app.listen(3000);

License

The MIT License (MIT) Copyright (c) 2012 Mac Angell

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

npm loves you