UNPKG

@security-alliance/octokit-plugin-cache

Version:

Octokit plugin for caching GitHub API responses

33 lines (32 loc) 1.03 kB
import { endpoint } from "@octokit/endpoint"; import { RequestError } from "@octokit/request-error"; function calculateCacheKey(options) { return endpoint(options).url; } async function wrapRequest(state, request, options) { if (options.method !== "GET") return await request(options); const cacheKey = calculateCacheKey(options); const cachedResponse = state.cache.get(cacheKey); if (cachedResponse !== void 0) { if (cachedResponse.headers.etag) { options.headers["if-none-match"] = cachedResponse.headers.etag; } if (cachedResponse.headers["last-modified"]) { options.headers["if-modified-since"] = cachedResponse.headers["last-modified"]; } } try { const response = await request(options); if (response.status === 200) { state.cache.set(cacheKey, response); } return response; } catch (e) { if (e instanceof RequestError && e.status === 304 && cachedResponse !== void 0) return cachedResponse; throw e; } } export { calculateCacheKey, wrapRequest };