@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) • 3.37 kB
JavaScript
"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.AppAdapter = void 0;
const remote_cache_handler_1 = require("./remote-cache-handler");
class AppAdapter {
constructor({ CacheHandler, buildId, cacheUrl, cacheMode = "isomorphic", options, buildReady, }) {
if (!CacheHandler || !cacheUrl || !buildId) {
throw new Error("Invalid configuration");
}
this.buildId = buildId;
this.cacheUrl = cacheUrl;
this.cacheMode = cacheMode;
this.cacheHandler = new CacheHandler(options);
this.remoteCacheHandler = new remote_cache_handler_1.RemoteCacheHandler(options, this.cacheUrl, this.buildId);
if (buildReady) {
this.remoteCacheHandler.deleteOld();
}
}
/**
* get cache
* @param key cache key
* @returns cached data
*/
get(key) {
return __awaiter(this, void 0, void 0, function* () {
if (this.cacheMode === "remote") {
const data = yield this.remoteCacheHandler.get(key);
return data;
}
else {
const data = yield this.cacheHandler.get(key);
return data;
}
});
}
/**
* 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* () {
if (this.cacheMode === "remote") {
const savedData = yield this.remoteCacheHandler.set(key, data, ctx);
return savedData;
}
else if (this.cacheMode === "isomorphic") {
const savedData = yield this.cacheHandler.set(key, data, ctx);
yield this.remoteCacheHandler.set(key, data, ctx);
return savedData;
}
else {
const savedData = yield this.cacheHandler.set(key, data, ctx);
return savedData;
}
});
}
/**
* revalidate tag in cache
* @param tag cache tag
*/
revalidateTag(tag) {
return __awaiter(this, void 0, void 0, function* () {
if (this.cacheMode === "remote") {
yield this.remoteCacheHandler.revalidateTag(tag);
}
else if (this.cacheMode === "isomorphic") {
yield this.remoteCacheHandler.revalidateTag(tag);
yield this.cacheHandler.revalidateTag(tag);
}
else {
yield this.cacheHandler.revalidateTag(tag);
}
});
}
}
exports.AppAdapter = AppAdapter;