@bbc/http-transport-cache

中文文档
6.0.1发布于 2026/10/15Apache-2.0CommonJS近 30 天下载 3218

Caching middleware

原始使用文档
文档目录8 节
  1. Installation
  2. Usage
  3. Features
  4. Events
  5. Middleware Options
  6. Cache version
  7. Cache Key Structure
  8. Test

NPM downloads npm license github-issues stars forks

HTTP Transport Cache

A HTTP spec compliant caching layer for http-transport.

Installation

pnpm install --save http-transport-cache

Usage

Configure response caching based on max-age:

const cache = require('@bbc/http-transport-cache');
const Catbox = require('@hapi/catbox');
const HttpTransport = require('@bbc/http-transport');

const catbox = new Catbox.Client(new Memory());

const url = 'http://example.com/';

const client = HttpTransport.createBuilder()
      .use(cache.maxAge(catbox))
      .createClient();

      const body = await client.get(url)
        .asBody();

      console.log(body);

Configure stale-if-error:

const cache = require('@bbc/http-transport-cache');
const Catbox = require('catbox');
const HttpTransport = require('@bbc/http-transport');

const catbox = new Catbox.Client(new Memory());

const url = 'http://example.com/';

const client = HttpTransport.createClient()
      .use(cache.staleIfError(catbox))
      .createClient();

      const body = await client.get(url)
        .asBody();

      console.log(body);

Listening to Events:

const { events, maxAge } = require('@bbc/http-transport-cache');

const stats = require('@ibl/stats');
const Catbox = require('catbox');
const HttpTransport = require('@bbc/http-transport');

const catbox = new Catbox.Client(new Memory());

const url = 'http://example.com/';

const client = HttpTransport.createBuilder()
  .use(cache.maxAge(catbox, {
    name: `theservice`,
  }))
  .createClient();

events.on(`cache.theservice.read_time`, (ctx) => {
  stats.timing(`timingstat.read_time`, ctx.duration);
});

Features

FeatureDescription
WarningsThe cached response only contains the simplified http-transport request and response so as not to waste cache space.
Max AgeResponses are stored for the duration of the max-age directive and are used before any requests are made.
Stale If ErrorIn order to ensure a resilient service even during errors, http responses can include a cache-control directive called stale-if-error which means we can use a cached response for that period whilst the service is erroring. To do this a separate response blob is stored for the stale period and on error this response is used alongside the body which is stored for the higher of either max-age or stale-if-error.
No StoreIf no-store directive is present in the response, it will not be stored / cached anywhere.
PrivateIf private directive is present in the response, it will not be stored by shared cache. The response will only be stored in a private cache intended for a single user.

Events

  • hit
  • miss
  • error
  • timeout
  • stale
  • read_time
  • write_time
  • connection_error

Middleware Options

Both maxage and staleIfError accept an options object.

PropertytypemoduleDescription
ignoreCacheErrorsbooleanmaxAge,staleIfErrorcache.maxAge will return a cache miss when this property is true. Setting this property true for cache.staleIfError will rethrow the original error (not the cache lookup error). ignoreCacheErrors is false by default.
timeoutintegermaxAgeTimeouts a cache lookup after a specified number of ms. By default, no timeout is specified.
connectionTimeoutintegermaxAge,staleIfErrorTimeouts the attempt to connect to a cache after a specified number of ms. By default, no timeout is specified.
includeCacheStatusInCtxbooleanmaxAge,staleIfErrorWhen present, a cacheStatus array - recording all cache events, will be set in context for use by other plugins. includeCacheStatusInCtx is false by default.

Cache version

The cache verison is stored in the config.json, this is distinct from the library version in the package.json. The cache version is used in the cache key and is intended to reduce cache fragmentation in a scenario where multiple different versions of this library might be in use across a single estate.

The cache version must be incremented if a change is made to the data stored in the cache that would be incompatible with the existing version. Otherwise it should not be changed.

Cache Key Structure

The cache uses catbox to provide a simple pluggable interface, this supports segmenting the cache as well as IDs, thus the following segments are used:

  • http-transport:{version}:response - Basic response from a call cached for the duration of the max-age value key on just the URL of the response.
  • http-transport:{version}:staleResponse - Stale response from a called cached for the stale-if-error value keyed on just the URL of the response.

Additionally, cache keys can be configured by passing a varyOn option. varyOn should contain an array of request header names which the cache should additionally vary on; for some use-cases, requests made to the same endpoint but with differing values for certain headers elicit different responses - and therefore cannot share the same cached response e.g.accept-language. By letting http-transport-cache know which headers to vary on, a unique cache key will be constructed which also contains said headers and their values.

Example:

We make a GET request to the following URL: www.example.com/some-cacheable-path.

We vary on accept-language and accept. These headers will exist in the request. We pass in varyOn (an array of request headers we vary on) together with other options to configure the plugin.

const opts = {
  timeout: 2000,
  varyOn: [
    'accept-language',
    'accept'
  ]
};

On the first request, the value of accept-language is en and accept is application/json. The resulting key will be:

  • GET:www.example.com/some-cacheable-path:accept-language=en,accept=application/json

On the second request, the value of accept-language is fr and accept is text/html. The resulting key will be:

  • GET:www.example.com/some-cacheable-path:accept-language=fr,accept=text/html

This way we avoid overwritting data in the store.

Test

pnpm test

To generate a test coverage report:

pnpm run coverage

版本与发布记录

@bbc/http-transport-cache 共发布 61 个版本,首次发布于 2017/09/05;过去 12 个月发布了 2 个版本。

版本发布日期距今
6.0.1latest2026/10/1523 天前
6.0.02026/10/1523 天前
5.0.02024/12/061.9 年前
4.4.02024/10/152 年前
4.3.12024/02/092 年前
4.3.02023/11/202 年前

其他发布通道:beta-swr → 1.3.8。

关于 @bbc/http-transport-cache 的常见问题

@bbc/http-transport-cache 是什么?

Caching middleware

如何安装 @bbc/http-transport-cache?

在项目目录运行 npm install @bbc/http-transport-cache,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@bbc/http-transport(^5.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@bbc/http-transport-cache 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/bbc__http-transport-cache 是否存在。

@bbc/http-transport-cache 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@bbc/http-transport-cache 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@bbc/http-transport-cache 可以商用吗?

@bbc/http-transport-cache 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@bbc/http-transport-cache 的下载量有多少?

根据 npm 官方下载统计,@bbc/http-transport-cache 在 2026/10/08 – 2026/11/06 这 30 天内被下载 3,218 次,日均约 107 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@bbc/http-transport-cache 还在维护吗?

最新版本 6.0.1 发布于 2026/10/15(23 天前);至今共发布 61 个版本,其中过去 12 个月发布了 2 个;首次发布于 2017/09/05。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。