UNPKG

@prezly/theme-kit-nextjs

Version:

Data layer and utility library for developing Prezly themes with NextJS

60 lines (59 loc) 2.97 kB
var _excluded = ["ttl", "prefix"]; function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; } /* eslint-disable no-console */ import stableStringify from 'json-stable-stringify'; import { createClient } from 'redis'; var CONNECTIONS = new Map(); export function createRedisCache(_ref) { var _CONNECTIONS$get; var { ttl, prefix = '' } = _ref, options = _objectWithoutProperties(_ref, _excluded); var connectionKey = stableStringify(options); var connection = (_CONNECTIONS$get = CONNECTIONS.get(connectionKey)) !== null && _CONNECTIONS$get !== void 0 ? _CONNECTIONS$get : createClient(options).on('error', error => console.error(error)).connect(); CONNECTIONS.set(connectionKey, connection); function createCache() { var namespacePrefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; return { get(key, latestVersion) { return _asyncToGenerator(function* () { var client = yield connection; var cached = yield client.get("".concat(namespacePrefix).concat(key)); if (!cached) { return undefined; } var entry = JSON.parse(cached); if (entry.version < latestVersion) { // the entry is stale and cannot be used anymore return undefined; } if (ttl) { client.expire("".concat(namespacePrefix).concat(key), ttl); // bump TTL on entries access } return entry.value; })(); }, set(key, value, version) { return _asyncToGenerator(function* () { var client = yield connection; var entry = { value, version }; yield client.set("".concat(namespacePrefix).concat(key), JSON.stringify(entry), { EX: ttl }); })(); }, namespace(namespace) { return createCache("".concat(namespacePrefix).concat(namespace, ":")); } }; } return createCache(prefix); }