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-cash

v4.1.1

Published

HTTP response caching for Koa. HTTP response caching for Koa. Supports Redis, in-memory store, and more!

Downloads

13,183

Readme

koa-cash

build status code coverage code style styled with prettier made with lass license npm downloads

HTTP response caching for Koa. Supports Redis, in-memory store, and more!

Table of Contents

Features

Caches the response based on any arbitrary store you'd like.

  • Handles JSON and stream bodies
  • Handles gzip compression negotiation (if options.compression is set to true as of v4.0.0)
  • Handles 304 responses

:tada: Pairs great with @ladjs/koa-cache-responses :tada:

Install

NPM

npm install koa-cash

Yarn

yarn add koa-cash

Usage

import LRU from 'lru-cache';
import koaCash from 'koa-cash';

// ...
const cache = new LRU();
app.use(koaCash({
  get: (key) => {
    return cache.get(key);
  },
  set(key, value) {
    return cache.set(key, value);
  },
}))

app.use(async ctx => {
  // this response is already cashed if `true` is returned,
  // so this middleware will automatically serve this response from cache
  if (await ctx.cashed()) return;

  // set the response body here,
  // and the upstream middleware will automatically cache it
  ctx.body = 'hello world!';
});

API

app.use(koaCash(options))

Options are:

maxAge

Default max age (in milliseconds) for the cache if not set via await ctx.cashed(maxAge).

threshold

Minimum byte size to compress response bodies. Default 1kb.

compression

If a truthy value is passed, then compression will be enabled. This value is false by default.

setCachedHeader

If a truthy value is passed, then X-Cached-Response header will be set as HIT when response is served from the cache. This value is false by default.

methods

If an object is passed, then add extra HTTP method caching. This value is empty by default. But GET and HEAD are enabled.

Eg: { POST: true }

hash()

A hashing function. By default, it's:

function hash(ctx) {
 return ctx.response.url; // same as ctx.url
}

ctx is the Koa context and is also passed as an argument. By default, it caches based on the URL.

get()

Get a value from a store. Must return a Promise, which returns the cache's value, if any.

function get(key, maxAge) {
  return Promise;
}

Note that all the maxAge stuff must be handled by you. This module makes no opinion about it.

set()

Set a value to a store. Must return a Promise.

function set(key, value, maxAge) {
  return Promise;
}

Note: maxAge is set by .cash = { maxAge }. If it's not set, then maxAge will be 0, which you should then ignore.

Example

Using a library like lru-cache, though this would not quite work since it doesn't allow per-key expiration times.

const koaCash = require('koa-cash');
const LRU = require('lru-cache');

const cache = new LRU({
  maxAge: 30000 // global max age
})

app.use(koaCash({
  get (key, maxAge) {
    return cache.get(key)
  },
  set (key, value) {
    cache.set(key, value)
  }
}))

See @ladjs/koa-cache-responses test folder more examples (e.g. Redis with ioredis).

Max age (optional)

const cached = await ctx.cashed(maxAge) // maxAge is passed to your caching strategy

This is how you enable a route to be cached. If you don't call await ctx.cashed(), then this route will not be cached nor will it attempt to serve the request from the cache.

maxAge is the max age passed to get().

If cached is true, then the current request has been served from cache and you should early return. Otherwise, continue setting ctx.body= and this will cache the response.

CashClear

ctx.cashClear('/')

This is a special method available on the ctx that you can use to clear the cache for a specific key.

Notes

  • Only GET and HEAD requests are cached. (Unless overridden)
  • Only 200 responses are cached. Don't set 304 status codes on these routes - this middleware will handle it for you
  • The underlying store should be able to handle Date objects as well as Buffer objects. Otherwise, you may have to serialize/deserialize yourself.

Contributors

| Name | Website | | ---------------- | ------------------------- | | Jonathan Ong | http://jongleberry.com | | Nick Baugh | http://niftylettuce.com |

License

MIT © Jonathan Ong

Links