UNPKG

@security-alliance/octokit-plugin-cache

Version:

Octokit plugin for caching GitHub API responses

62 lines (59 loc) 1.77 kB
// pkg/dist-src/index.js import { Octokit } from "@octokit/core"; import { LRUCache } from "lru-cache"; // pkg/dist-src/wrap-request.js 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; } } // pkg/dist-src/index.js var cache = (octokit, octokitOptions) => { const { enabled = true, options = { max: 1024, ttl: 1e3 * 60 * 60 * 6, maxEntrySize: 1024 * 16, sizeCalculation: (value) => { const contentLengthHeader = value.headers["content-length"]; if (contentLengthHeader === void 0) return 1; return parseInt(contentLengthHeader.toString()); } } } = octokitOptions.cache || {}; if (!enabled) { return {}; } const state = { cache: new LRUCache(options) }; octokit.hook.wrap("request", wrapRequest.bind(null, state)); return {}; }; export { cache };