UNPKG

cache-action

Version:

Save and restore files as a cache in GitHub Actions

56 lines (55 loc) 1.78 kB
async function fetchCacheService(method, body) { const url = process.env.ACTIONS_RESULTS_URL ?? "/"; const token = process.env.ACTIONS_RUNTIME_TOKEN ?? ""; return fetch(`${url}twirp/github.actions.results.api.v1.CacheService/${method}`, { body: JSON.stringify(body), method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, }); } async function handleCacheServiceError(res) { const contentType = res.headers.get("content-type"); if (contentType?.includes("application/json")) { const data = await res.json(); if (typeof data === "object" && data && "msg" in data) { throw new Error(`${data.msg} (${res.status.toFixed()})`); } } throw new Error(`${res.statusText} (${res.status.toFixed()})`); } export async function getCacheEntryDownloadUrl(key, version) { const res = await fetchCacheService("GetCacheEntryDownloadURL", { key, version, }); if (!res.ok) { await handleCacheServiceError(res); } return (await res.json()); } export async function createCacheEntry(key, version) { const res = await fetchCacheService("CreateCacheEntry", { key, version, }); if (!res.ok) { if (res.status == 409) return { ok: false, signed_upload_url: "" }; await handleCacheServiceError(res); } return (await res.json()); } export async function finalizeCacheEntryUpload(key, version, sizeBytes) { const res = await fetchCacheService("FinalizeCacheEntryUpload", { key, version, sizeBytes, }); if (!res.ok) { await handleCacheServiceError(res); } return (await res.json()); }