@rb2bv/cache-handler
Version:
Next.js self-hosting simplified.
79 lines (78 loc) • 2.34 kB
JavaScript
// src/handlers/server.ts
function createHandler({ baseUrl, timeoutMs }) {
return {
name: "server",
async get(key, { implicitTags }) {
const url = new URL("/get", baseUrl);
url.searchParams.set("key", key);
url.searchParams.set("implicitTags", JSON.stringify(implicitTags));
const response = await fetch(url, {
signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : void 0,
// @ts-expect-error -- act as an internal fetch call
next: {
internal: true
}
});
if (response.status === 404) {
return null;
}
if (!response.ok) {
throw new Error(`get error: ${response.status}`);
}
const string = await response.text();
return JSON.parse(string);
},
async set(key, cacheHandlerValue) {
const url = new URL("/set", baseUrl);
const response = await fetch(url, {
method: "POST",
body: JSON.stringify([key, JSON.stringify(cacheHandlerValue)]),
headers: {
"Content-Type": "application/json"
},
signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : void 0,
// @ts-expect-error -- act as an internal fetch call
next: {
internal: true
}
});
if (!response.ok) {
throw new Error(`set error: ${response.status}`);
}
},
async revalidateTag(tag) {
const url = new URL("/revalidateTag", baseUrl);
const response = await fetch(url, {
method: "POST",
body: JSON.stringify([tag]),
headers: {
"Content-Type": "application/json"
},
signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : void 0,
// @ts-expect-error -- act as an internal fetch call
next: {
internal: true
}
});
if (!response.ok) {
throw new Error(`revalidateTag error: ${response.status}`);
}
},
async delete(key) {
const url = new URL(`/${key}`, baseUrl);
const response = await fetch(url, {
method: "DELETE",
// @ts-expect-error -- act as an internal fetch call
next: {
internal: true
}
});
if (!response.ok) {
throw new Error(`delete error: ${response.status}`);
}
}
};
}
export {
createHandler as default
};