cache.js

ABOUT

This module is concerned with: 1) consistently setting caching headers in the browser; 2) sending data to be cached in accordance with the caching policy and; 3) providing role-based cache fetching services to ensure that authorized personas (users, services) are able to view fetched data in accordance with their authorization*

REQUIREMENTS & ASSUMPTIONS

require('../security.json')
require('redis')
// const PORT = require('./secrets').fetchSecret('CACHE_PORT') || 9000
require('./secrets').fetchSecret('REDIS_PORT')
const client = redis.createClient(REDIS_PORT)
  • _spartan natively supports redis for caching services. If you are using another database or service for this purpose, you may need to adjust these values to point to your listening PORT (e.g. ‘CACHE_PORT’ commented out) and/or provide connection creds for your cache client (e.g. ‘const client’)
  • _spartan assumes information related to caching services to be SECRET. The port & connection creds to the cache client should be saved in the .env file. See secrets for more information on how to set this up.

Want native support for other caching services (like memcache)? Submit an issue in github as a feature request or thumbs-up the existing issue!

AVAILABLE METHODS

Module Instantiation

method name description params returns
N/A returns functions create cache headers, send data to be cached and fetch data from cache (by route) N/A cacheHeaders, setCache, getCache function, OR Error if cache policy is disabled

USAGE

// ex: in app.js -> 
const cache = require('./security').cache

Setting Cache Headers

method name description params returns
cacheHeaders() sets the cache headers as configured in the policy N/A cacheHeaders (Object) or Error

USAGE

// where app = express() or similar
app.get('/route', function(request, response, next){
    let cacheHeaders = cache.cacheHeaders() //returns object w/ values for 'Cache-Control', 'Vary', 'Pragma'
    response.set(cacheHeaders)
})

By default _spartan takes a strict ‘no-cache’ policy across the board. You can overload this per-route by setting securityHeaders.config.caching.routeOverload : true in security.json

Send Data to Cache

method name description params returns
setCache() sends data in the route to the cache for the time specified in securityHeaders.config.caching.ttl route, dataToCache, callback Success message String or Error

USAGE

// where app = express() or similar
app.get('/route', function(request, response, next){
  cache.setCache(request.url, response, function(err, message) {
    if (err) {
      console.log(err)
      next(err)
    }
    else {
      console.log(message)
      // next thing
      ...
    }
  })
})

Get Data from Cache

method name description params returns
getCache() fetches data for the route from the cache assuming it is still available according to securityHeaders.config.caching.ttl route, dataToCache, callback Success message String or Error

USAGE

// where app = express() or similar
app.get('/route', function(request, response, next){
  cache.getCache(request.url, response, function(err, data) {
    if (err && data === null) {
      console.log(err)
      next(err)
    } else if (err && data === undefined) {
      // ttl has expired, generate new data and send that
    }
    else {
      response.send(data)
      // next thing
      ...
    }
  })
})

ERRORS

  • (‘cache/cache-policy-disabled’) => thrown if the cache policy object is not enabled. To change this, change securityHeaders.config.caching.enabled = true in security.json
  • (‘cache/route-overload-disabled’) => thrown if an attempt to overload cache settings outside of policy settings was discovered (fires on ‘setCache())
  • (‘cache/could-not-fetch-data’) => thrown if there was a problem fetching cached data
  • (‘cache/ttl-expired’) => thrown if the cached data is expired and new data should be generated