npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@outofsync/request-utils-response-cache

v1.2.1

Published

A response cache for use with ExpressJS

Downloads

4

Readme

request-utils-response-cache

NPM

Version Downloads Build Status Codacy Badge Codacy Coverage Badge Dependencies

request-utils-response-cache is an inline, response caching mechanism for ExpressJS and request-utils which uses a connected ObjectKeyCache or Redis.

Response Caching is highly recommended for any client facing Express application or APIs that are build on top of Express that may be under even the most modest of loads.

A response's res.locals data are cached based on the following HTTP Request criteria:

  • HTTP Method (optional)
  • Request URL
  • HTTP Headers (optional)
  • HTTP Query Params (optional)
  • HTTP Form Body Params
  • Express Parameter value (req.params)

Any etag, if-match, if-none-match, if-modified-since, or if-unmodified-since headers are stripped from the request before checking against the cache for a matching request. Additionally, if the header cache-control set to no-cache is passed in the request, then the cache checking is skipped.

If two requests are made with the same criteria, then the second request will be served from cache. By default, responses are cached on a 5-minute fixed window based on the timestamp of the initial cached response. After the timeframe has elapsed, the response is fully handled and the results can be cached again.

If there are any unexpected errors during the cache retrieval process, then the process fails silently and the request is handled as if it were not cached.

If additional manipulation of the request is desired then it is possible to provide an onCacheMiss(req, res) and onCacheHit(req, res, data) to the configuration of the Response Cache

Installation

npm install @outofsync/request-utils-response-cache

Usage

const ResponseCache = require('@outofsync/request-utils-response-cache');
let responseCache = new ResponseCache('responses', {
  expire: 300000, // Five minutes
  onCacheHit: ((req, res, data) => {
    res.set('Content-Type', 'application/json');
  })
});

function sendResponse(req, res, next) {
  if (!res.headersSent) {
    res.set('Content-Type', 'application/json');
    for (const header in res.locals.headers) {
      if (res.locals.headers.hasOwnProperty(header)) {
        res.header(header, res.locals.headers[header]);
      }
    }
    res.status(res.locals.status);
    res.json(__.omit(res.locals.body, ['cacheExpiration']));
  }
  next();
}

// Later within the expressJS request stack
// Before other processing, check cache
app.use(responseCache.handler);

// Do other processing
// app.use...

// After other processing
app.use(responseCache.store); // This only stores when the req.needsCache is set

// Process the res.locals and send response
app.use(sendResponse);

API Reference

constructor(cacheNamespace [, config] [, cache] [, log])

Create a new ResponseCache with the passed cacheNamespace, config, cache, and log. A cacheNamespace is required to scope the Response Cache to scope other values which may be in use within the cache.

handler(req, res, next)

An ExpressJS handler to check the current request against cache. If the cache exists, then it is retrieved and placed in res.locals and sets req.usedCache to true. If the cache does not exist and the request should be cached, then this sets the req.needsCache to true. This should occur early in the ExpressJS stack.

  app.use(responseCache.handler);

store(req, res, next)

An ExpressJS handler to store the current request when the handler indicates that the current request is not cached by the req.needsCache. This should occur just before the response is sent in the ExpressJS stack.

  app.use(responseCache.handler);

Appendix

Configuration Object

The configuration parameter expects and object that contains the following (with defaults provided below):

{
  expire: 300000 // every 5 minute window (in mSec)
  ignoreHeaders: false,
  ignoreMethod: false,
  ignoreQuery: false,
  onCacheHit: (req, res, data) => {

  },
  onCacheMiss: (req, res) => {

  }
}

|parameter|type|description| |---------|----|-----------| |expire|Integer|Number of milliseconds for the fixed window for the initial cache.| |onCacheHit|Function(req, res, data) or null|A function accepting a HTTPRequest, a HTTPResponse, object data. When a request hits the cache then this function is called so additional data processing can occur.| |onCacheMiss|Function(req, res) or null|A function accepting a HTTPRequest, a HTTPResponse. When a request misses the cache then this function is called so additional data processing can occur.| |ignoreHeaders|Boolean|Skips the request headers when calculating the cache key| |ignoreMethod|Boolean|Skips the request method when calculating the cache key| |ignoreQuery|Boolean|Skips the query parameters when calculating the cache key|

Cache Object

The Cache object can be a active and promisified Redis connect, or an active ObjectKeyCache. If no value is set, then the response cache will create an internal Object Key Cache and use it.

Logging Object

The Logging object is an instance of any logging library, such as Winston or Bunyan, which support the .error(...), .info(...), .debug(...), and .log(...) methods. If this is not provided, then any debug or error messages are sent to /dev/null through the use of LogStub.