### CachePolicy Constructor Options Example Source: https://github.com/kornelski/http-cache-semantics/blob/main/README.md Provides an example of the required `request` and `response` objects, including their `headers` properties (with lowercase header names), and demonstrates the usage of various `options` for the `CachePolicy` constructor, such as `shared`, `cacheHeuristic`, `immutableMinTimeToLive`, and `ignoreCargoCult`. ```javascript const request = { url: '/', method: 'GET', headers: { accept: '*/*', }, }; const response = { status: 200, headers: { 'cache-control': 'public, max-age=7234', }, }; const options = { shared: true, cacheHeuristic: 0.1, immutableMinTimeToLive: 24 * 3600 * 1000, // 24h ignoreCargoCult: false, }; ``` -------------------------------- ### Complete Cache Usage Example Source: https://github.com/kornelski/http-cache-semantics/blob/main/README.md This comprehensive example demonstrates the typical workflow of using the http-cache-semantics library. It covers fetching data from a cache, handling cache misses by making a request to the origin and storing the response, evaluating existing cache entries against new requests, performing synchronous or asynchronous revalidation, and updating the cache with new information. ```javascript let cached = cacheStorage.get(incomingRequest.url); // Cache miss - make a request to the origin and cache it if (!cached) { const newResponse = await makeRequest(incomingRequest); const policy = new CachePolicy(incomingRequest, newResponse); cacheStorage.set( incomingRequest.url, { policy, body: newResponse.body }, policy.timeToLive() ); return { // use responseHeaders() to remove hop-by-hop headers that should not be passed through proxies headers: policy.responseHeaders(), body: newResponse.body, } } // There's something cached, see if it's a hit let { revalidation, response } = cached.policy.evaluateRequest(incomingRequest); // Revalidation always goes first if (revalidation) { // It's very important to update the request headers to make a correct revalidation request incomingRequest.headers = revalidation.headers; // Same as cached.policy.revalidationHeaders() // The cache may be updated immediately or in the background, // so use a Promise to optionally defer the update const updatedResponsePromise = makeRequest(incomingRequest).then(() => { // Refresh the old response with the new information, if applicable const { policy, modified } = cached.policy.revalidatedPolicy(incomingRequest, newResponse); const body = modified ? newResponse.body : cached.body; // Update the cache with the newer response if (policy.storable()) { cacheStorage.set( incomingRequest.url, { policy, body }, policy.timeToLive() ); } return { headers: policy.responseHeaders(), // these are from the new revalidated policy body, } }); if (revalidation.synchronous) { // If synchronous, then you MUST get a reply from the server first return await updatedResponsePromise; } // If not synchronous, it can fall thru to returning the cached response, // while the request to the server is happening in the background. } return { headers: response.headers, // Same as cached.policy.responseHeaders() body: cached.body, } ``` -------------------------------- ### Revalidation Headers Source: https://github.com/kornelski/http-cache-semantics/blob/main/README.md The `revalidationHeaders()` method (implicitly used via `revalidation.headers` in the example) generates the necessary HTTP headers for revalidating a cached response with the origin server. This ensures that the server can correctly determine if the cached content is still valid. ```javascript // Used implicitly: incomingRequest.headers = revalidation.headers; // Same as cached.policy.revalidationHeaders() ``` -------------------------------- ### Basic Usage: Storing a Response Source: https://github.com/kornelski/http-cache-semantics/blob/main/README.md Demonstrates how to create a CachePolicy object for a request and response, check if it's storable, and store it along with the response body in a cache. This involves instantiating CachePolicy with request, response, and options, checking `storable()`, and then saving the policy and body with a TTL obtained from `timeToLive()`. ```javascript const policy = new CachePolicy(request, response, options); if (!policy.storable()) { // throw the response away, it's not usable at all return; } // Cache the data AND the policy object in your cache // (this is pseudocode, roll your own cache (lru-cache package works)) letsPretendThisIsSomeCache.set( request.url, { policy, body: response.body }, // you only need to store the response body. CachePolicy holds the headers. policy.timeToLive() ); ``` -------------------------------- ### Suggest Time To Live Source: https://github.com/kornelski/http-cache-semantics/blob/main/README.md The `timeToLive()` function suggests a time in milliseconds for how long a cache entry may remain useful. This is not a strict freshness check; it allows for extended usability with `stale-if-error` and `stale-while-revalidate` directives. The cache entry might still be usable after `timeToLive()` returns 0 or less, especially if clients permit stale responses. ```javascript // Example usage is within the larger example below. ``` -------------------------------- ### Basic Usage: Retrieving and Validating a Cached Response Source: https://github.com/kornelski/http-cache-semantics/blob/main/README.md Illustrates how to retrieve a cached response using a new request, check if the cached policy satisfies the new request without revalidation using `satisfiesWithoutRevalidation()`, and return updated headers and body if valid. If not valid, it suggests checking revalidation headers for advanced usage. ```javascript // And later, when you receive a new request: const { policy, body } = letsPretendThisIsSomeCache.get(newRequest.url); // It's not enough that it exists in the cache, it has to match the new request, too: if (policy && policy.satisfiesWithoutRevalidation(newRequest)) { // OK, the previous response can be used to respond to the `newRequest`. // Response headers have to be updated, e.g. to add Age and remove uncacheable headers. return { headers: policy.responseHeaders(), body, } } // Cache miss. See revalidationHeaders() and revalidatedPolicy() for advanced usage. ``` -------------------------------- ### Generate Revalidation Headers Source: https://github.com/kornelski/http-cache-semantics/blob/main/README.md Generates updated, filtered request headers to send to the origin server for cache revalidation. This allows the origin server to return a 304 status if the cached response is still fresh. Unrelated caching headers are passed through. ```JavaScript updateRequest.headers = cachePolicy.revalidationHeaders(updateRequest); ``` -------------------------------- ### Serialize and Deserialize CachePolicy Source: https://github.com/kornelski/http-cache-semantics/blob/main/README.md The `toObject()` and `fromObject(json)` methods allow for the serialization and deserialization of a `CachePolicy` object. `toObject()` converts the policy into a JSON-serializable format, while `fromObject(obj)` reconstructs the `CachePolicy` instance from this object. ```javascript let obj = policy.toObject(); let policy = CachePolicy.fromObject(obj); ``` -------------------------------- ### Evaluate Request for Cache Action Source: https://github.com/kornelski/http-cache-semantics/blob/main/README.md The `evaluateRequest(newRequest)` function determines the next action based on an incoming request and the cached data. It returns an object that may contain either a `revalidation` object (specifying headers and synchronization requirements for a server request) or a `response` object (containing updated headers for serving from cache). Both can be present. ```javascript let { revalidation, response } = cached.policy.evaluateRequest(incomingRequest); ``` -------------------------------- ### Filter Response Headers Source: https://github.com/kornelski/http-cache-semantics/blob/main/README.md The `responseHeaders()` function updates and filters the response headers to be returned to clients receiving a cached response. It is crucial for proxies to remove hop-by-hop headers and adjust the 'Age' header to prevent incorrect cache timing. ```javascript cachedResponse.headers = cachePolicy.responseHeaders(); ``` -------------------------------- ### Revalidated Policy Source: https://github.com/kornelski/http-cache-semantics/blob/main/README.md The `revalidatedPolicy(request, newResponse)` function is used after a revalidation request to the server. It takes the original request and the new response from the server to determine the updated cache policy and whether the response body was modified. This is essential for correctly updating the cache with fresh information. ```javascript const { policy, modified } = cached.policy.revalidatedPolicy(incomingRequest, newResponse); ``` -------------------------------- ### Update Cache Policy with Revalidation Response Source: https://github.com/kornelski/http-cache-semantics/blob/main/README.md Updates the cache policy after receiving a new response from the origin server. It returns a new CachePolicy object with updated HTTP headers and a boolean indicating if the response body has changed. ```JavaScript { policy: newPolicy, modified: true } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.