or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-workbox-cacheable-response

This library takes a Response object and determines whether it's cacheable based on a specific configuration.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/workbox-cacheable-response@7.3.x

To install, run

npx @tessl/cli install tessl/npm-workbox-cacheable-response@7.3.0

index.mddocs/

Workbox Cacheable Response

Workbox Cacheable Response is a TypeScript library that takes a Response object and determines whether it's cacheable based on a specific configuration. It provides flexible control over which HTTP responses should be stored in the cache by evaluating status codes and headers according to configurable rules.

Package Information

  • Package Name: workbox-cacheable-response
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install workbox-cacheable-response
  • Dependencies: workbox-core (^7.3.0)

Core Imports

import { CacheableResponse, CacheableResponsePlugin, CacheableResponseOptions } from "workbox-cacheable-response";

For CommonJS:

const { CacheableResponse, CacheableResponsePlugin } = require("workbox-cacheable-response");

Basic Usage

import { CacheableResponse, CacheableResponsePlugin, CacheableResponseOptions } from "workbox-cacheable-response";

// Direct usage for response evaluation
const cacheableResponse = new CacheableResponse({
  statuses: [0, 200],
  headers: { 'X-Is-Cacheable': 'true' }
});

// Check if a response is cacheable
const response = await fetch('/api/data');
const isCacheable = cacheableResponse.isResponseCacheable(response);

// Plugin usage with Workbox strategies
const plugin = new CacheableResponsePlugin({
  statuses: [0, 200, 404]
});

Architecture

The package is built around two main components:

  • CacheableResponse: Core class that implements the caching rules logic and evaluates responses
  • CacheableResponsePlugin: Workbox plugin wrapper that integrates with Workbox caching strategies via the cacheWillUpdate lifecycle
  • Configuration Interface: CacheableResponseOptions provides type-safe configuration for both classes

Capabilities

Response Cacheability Evaluation

Direct evaluation of HTTP responses based on configurable rules for status codes and headers.

/**
 * Core class that allows setting up rules determining what status codes 
 * and/or headers need to be present for a Response to be considered cacheable
 */
class CacheableResponse {
  /**
   * Creates a new CacheableResponse instance. At least one of statuses or headers must be provided.
   * @param config - Configuration options for cacheability rules (defaults to empty object)
   * @throws WorkboxError when neither statuses nor headers are provided
   */
  constructor(config: CacheableResponseOptions = {});
  
  /**
   * Checks a response to see whether it's cacheable based on configuration
   * @param response - The response whose cacheability is being checked
   * @returns true if the Response is cacheable, false otherwise
   */
  isResponseCacheable(response: Response): boolean;
}

Workbox Strategy Integration

Plugin implementation for seamless integration with Workbox caching strategies.

/**
 * A class implementing the cacheWillUpdate lifecycle callback for integration 
 * with Workbox's built-in strategies
 */
class CacheableResponsePlugin implements WorkboxPlugin {
  /**
   * Creates a new CacheableResponsePlugin instance
   * @param config - Configuration options for cacheability rules
   */
  constructor(config: CacheableResponseOptions);
  
  /**
   * Workbox lifecycle callback that determines if a response should be cached
   * @param options - Object containing the response to evaluate
   * @param options.request - The request object
   * @param options.response - The response object to evaluate
   * @param options.event - The ExtendableEvent associated with the request
   * @param options.state - Plugin state object
   * @returns Promise resolving to the response if cacheable, null otherwise
   */
  cacheWillUpdate(options: {
    request: Request;
    response: Response;
    event: ExtendableEvent;
    state?: PluginState;
  }): Promise<Response | null>;
}

Types

/**
 * Configuration options for both CacheableResponse and CacheableResponsePlugin.
 * At least one of statuses or headers must be provided.
 */
interface CacheableResponseOptions {
  /** 
   * One or more status codes that a Response can have and be considered cacheable
   * @example [0, 200, 404]
   */
  statuses?: number[];
  
  /** 
   * A mapping of header names and expected values that a Response can have 
   * and be considered cacheable. If multiple headers are provided, only one needs to be present
   * @example { 'X-Is-Cacheable': 'true', 'Cache-Control': 'public' }
   */
  headers?: {[headerName: string]: string};
}

/**
 * Type representing plugin state object for Workbox plugins
 */
type PluginState = {[key: string]: any};

/**
 * Workbox plugin interface with lifecycle callbacks
 */
interface WorkboxPlugin {
  cacheWillUpdate?: (options: {
    request: Request;
    response: Response;
    event: ExtendableEvent;
    state?: PluginState;
  }) => Promise<Response | void | null | undefined>;
}

Usage Examples

Basic Response Evaluation

import { CacheableResponse, CacheableResponseOptions } from "workbox-cacheable-response";

// Create instance with status code rules
const config: CacheableResponseOptions = {
  statuses: [0, 200]
};
const cacheableResponse = new CacheableResponse(config);

// Evaluate a response
const response = await fetch('/api/users');
if (cacheableResponse.isResponseCacheable(response)) {
  // Cache the response
  await cache.put(request, response);
}

Header-Based Caching Rules

import { CacheableResponse } from "workbox-cacheable-response";

// Create instance with header rules
const cacheableResponse = new CacheableResponse({
  headers: { 'X-Is-Cacheable': 'true' }
});

const response = await fetch('/api/dynamic-content');
if (cacheableResponse.isResponseCacheable(response)) {
  // Only cache responses with the specific header
  await cache.put(request, response);
}

Combined Rules

import { CacheableResponse } from "workbox-cacheable-response";

// Both status and header conditions must be met
const cacheableResponse = new CacheableResponse({
  statuses: [200, 404],
  headers: { 'Content-Type': 'application/json' }
});

Workbox Strategy Integration

import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
import { CacheableResponsePlugin } from 'workbox-cacheable-response';

// Use with Workbox caching strategy
registerRoute(
  ({ request }) => request.destination === 'image',
  new StaleWhileRevalidate({
    cacheName: 'images',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200]
      })
    ]
  })
);

Error Handling

The package throws WorkboxError (from workbox-core) when:

  • Neither statuses nor headers are provided in the constructor configuration
  • Invalid parameter types are passed (in development mode only)

Development mode also provides detailed logging when responses are not cacheable, including:

  • Current cacheability criteria
  • Response status and headers
  • Full response details for debugging

Dependencies

This package depends on:

  • workbox-core: Provides core utilities including error handling, logging, and type definitions