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

koa-context-cache

v0.2.1

Published

Koa middleware that caches a field in the context object

Downloads

4

Readme

koa-context-cache

Middleware for koa that caches values applied to the context state by other middleware.

Example use case

You have an API endpoint and want to control access to that endpoint based on the Authorization header. To implement thhis, you have a middleware ensureAuth which checks the header and stores the result in ctx.state, something like the following.

const ensureAuth = async (ctx, next) => {
  const authToken = ctx.headers.authorization
  if (!authToken) return ctx.throw(401) // Unauthorized
  ctx.state.userinfo = await getUserFromToken(authToken)
  if (!ctx.state.userinfo.isAuthorized) return ctx.throw(403) // Forbidden
  await next()
}

router.get('/protected-endpoint', ensureAuth, async ctx => {
  // ...
})

However, that getUserFromToken function is slow or expensive - it has to make a request to another service, or to a database. Clients might be hitting the API frequently, so you want to cache the value of ctx.state.userinfo for a short period for each token.

Sidenote: in this contrived example you could just wrap a cache around getUserFromToken. But let's say ensureAuth is actually from a third-party library and you don't want to hack around in its internals.

This package allows you to wrap ensureAuth in a cache in the following way:

import koaContextCache from 'koa-context-cache'

const cachedAuth = koaContextCache({
  middleware: ensureAuth,
  getKeyFromContext: ctx => ctx.headers.Authorization,
  contextPropName: 'userinfo',
  ttl: 60 // seconds
})

router.get('/protected-endpoint', cachedAuth, async ctx => {
  // ...
})

When the first request comes in with a particular Authorization header, the ensureAuth middleware will be applied and when the request completes the resulting value of ctx.state.userinfo will be stored in a cache.

Any subsequent requests (within the TTL) that present the same Authorization header will have the cached value added to the context as ctx.state.userinfo without the ensureAuth middleware running.

API

The module exports a function which returns a middleware. The function accepts an options object with the following properties. See the example code above.

  • getKeyFromContext: a function that derives the cache key from the context. It will be passed the Koa context and should return a String.
  • middleware: middleware which will be applied if there is no cached value for the given key.
  • contextPropName: the name of the property of ctx.state which is to be cached; i.e. what is cached is the value of ctx.state[contextPropName].
  • ttl: time-to-live of the cache, in seconds.