adonis5-cache
Version:
Cache provider for AdonisJS 5
55 lines (54 loc) • 1.9 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const dayjs_1 = __importDefault(require("dayjs"));
const ramda_1 = require("ramda");
class InMemoryStorage {
constructor() {
this.cacheStorage = this.initCacheStorage;
}
get initCacheStorage() {
return { cacheRecords: {}, tags: {} };
}
async get(context, key) {
const { recordExpirationTime, recordValue = null } = this.cacheStorage[key] || {};
return recordValue !== null && dayjs_1.default().isBefore(dayjs_1.default(recordExpirationTime))
? context.deserialize(recordValue)
: null;
}
async getMany(context, keys) {
return Promise.all(keys.map((key) => this.get(context, key)));
}
async put(context, key, value, ttl) {
this.cacheStorage[key] = {
recordExpirationTime: dayjs_1.default().add(ttl, 'ms').toISOString(),
recordValue: context.serialize(value),
};
}
async putMany(context, cacheDictionary, ttl) {
await Promise.all(Object.entries(cacheDictionary).map(([key, value]) => this.put(context, key, value, ttl)));
}
async flush() {
this.cacheStorage = this.initCacheStorage;
}
async forget(key) {
const isExists = key in this.cacheStorage;
delete this.cacheStorage[key];
return isExists;
}
async addTag(tag, tagData) {
this.cacheStorage.tags[tag] = ramda_1.append(tagData, this.cacheStorage.tags[tag]);
}
async readTag(tag) {
return this.cacheStorage.tags[tag] || [];
}
async removeTag(tag) {
delete this.cacheStorage.tags[tag];
}
resolveTtl(ttlInMl) {
return ttlInMl;
}
}
exports.default = InMemoryStorage;