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*
require('../security.json')
require('redis')
// const PORT = require('./secrets').fetchSecret('CACHE_PORT') || 9000
require('./secrets').fetchSecret('REDIS_PORT')
const client = redis.createClient(REDIS_PORT)
.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!
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
...
}
})
})
securityHeaders.config.caching.enabled = true
in security.json