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

express-cache-middleware

v1.0.1

Published

An Express middleware designed to intercept responses and cache them.

Downloads

688

Readme

express-cache-middleware

An Express middleware designed to intercept responses and cache them.

https://nodei.co/npm/express-cache-middleware.svg?downloads=true&downloadRank=true&stars=true

Dependency Status Coverage Status Known Vulnerabilities

master: Build Status Inline docs

Usage

To use this middleware, first instantiate it. The first argument to the constructor must be a cache-manager .caching() instance, initialized with any backend you choose. The second argument is an optional object of options.

const express = require('express')
const ExpressCache = require('express-cache-middleware')
const cacheManager = require('cache-manager')

const cacheMiddleware = new ExpressCache(
	cacheManager.caching({
		store: 'memory', max: 10000, ttl: 3600
	})
)

Then, attach it to your Express app instance or Router. Any routes attached to the app or Router after this will be intercepted and cached.

// Layer the caching in front of the other routes
cacheMiddleware.attach(app)

// Attach the routes to be cached
app.all('*', (req, res) => {
	// ... do something expensive like a fetch() here ...
	res.send('response')
})

app.listen()

Please see the options for important information about handling incoming and outgoing data.

Options

getCacheKey

A function to get the cache key from the request. Provided with one argument: the request object from Express.

By default, this is a function that returns the request URL.

You may want to customize this function if you anticipate that there are things in your URL that you don't want in your cache key. For example, you can remove irrelevant query parameters or subdirectories by parsing the URL here and returning the cache key.

hydrate

Because this middleware is backend-agnostic, it makes no assumptions about what you want to do with cached data. By default, it just passes the streamed data out as the response, and what this data actually is will depend on your chosen cache-manager backend since no metadata side-channel is available.

This usually ends up as a response with Content-Type: application/octet-stream, which is not often what people want. To fix this, hydrate is run before the content is returned.

hydrate is called with four arguments:

  • req, the Express request object
  • res, the Express response object
  • data. the data returned from cache
  • cb, an optional callback function

Set any headers or perform any transformations on the returned data. Then, call the callback with (err, result) or return a Promise.

Note: hydrate is not called for the first response, where your route returns its original content-- only for cache hits.

Example for handling image responses:

const fileType = require('file-type')
const cacheMiddleware = new ExpressCache(
	cacheManager.caching({
		store: 'memory', max: 10000, ttl: 3600
	}), {
		hydrate: (req, res, data, cb) => {
			// Use file-type library to guess MIME type from Buffer.
			const guess = fileType(data.slice(0, 4101))
			if( guess ) {
				res.contentType(guess.mime)
			}

			cb(null, data)
		}
	}
)

// or with Promises:
const hydrateWithPromise = (res, data) => {
	return Promise.resolve(data)
}

// or with async/await:
const hydrateAsync = async (res, data) => {
	return data
}

Example for handling mixed content responses:

const hydrateManyThings = async (req, res, data) => {
  // Parse as JSON first
  try {
    JSON.parse(data)
    res.contentType('application/json')
    return data
  } catch ( err ) {}

  const guess = fileType(data.slice(0, 4101))
  if( guess ) {
    res.contentType(guess.mime)
  }
  return data
}

Changelog

1.0.1 Removes mung's json as it was setting cache multiple times. send will catch json as well. Alters Promise detection from hydrate functions-- async was not being detected as Promises. Updated dev dependencies, added babel-jest-assertions to ensure the tests are running properly, and minor linting

1.0.0 First full release, using fork of express-mung