UNPKG

@nimpl/cache-adapter

Version:

An adapter that allows you to use any cache handler on the client and server side and switch between them. Adds support for running next.js applications in multiple instances.

88 lines (87 loc) 2.9 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.RemoteCacheHandler = void 0; /* eslint-disable @typescript-eslint/no-explicit-any */ class RemoteCacheHandler { /** * remote cache handler * @param options next.js options * @param url server url * @param unique build id */ constructor(options, url, buildId) { // should we transfer options? this.options = options; const serverUrl = new URL(url); serverUrl.searchParams.set("buildId", buildId); this.url = serverUrl; } /** * get cache * @param key cache key * @returns cached data */ get(key) { return __awaiter(this, void 0, void 0, function* () { const url = new URL(this.url); url.searchParams.set("key", key); const resp = yield fetch(url.toString()); if (resp.status !== 200) return; return resp.json(); }); } /** * set cache * @param key cache key * @param data data to store * @param ctx next.js context */ set(key, data, ctx) { return __awaiter(this, void 0, void 0, function* () { const url = new URL(this.url); url.searchParams.set("key", key); yield fetch(url.toString(), { method: "POST", body: JSON.stringify({ data, ctx, }), }); }); } /** * revalidate tag in cache * @param tag cache tag */ revalidateTag(tag) { return __awaiter(this, void 0, void 0, function* () { const url = new URL(this.url); url.searchParams.set("key", tag); yield fetch(url.toString(), { method: "DELETE", }); }); } /** * revalidate tag in cache */ deleteOld() { return __awaiter(this, void 0, void 0, function* () { const url = new URL(this.url); yield fetch(url.toString(), { method: "PUT", }); }); } } exports.RemoteCacheHandler = RemoteCacheHandler;