@melchyore/adonis-cache
Version:
Cache package for AdonisJS V5
82 lines (81 loc) • 2.76 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const TaggableStore_1 = __importDefault(require("./TaggableStore"));
class Memcached extends TaggableStore_1.default {
constructor(client) {
super();
this.client = client;
}
/**
* In Memcached, TTL is expressed in seconds.
*/
calculateTTL(ttlInMilliseconds) {
return ttlInMilliseconds / 1000;
}
async get(key) {
const value = await this.client.get(this.buildKey(key));
return value ? this.deserialize(value.toString()) : null;
}
async many(keys) {
const records = {};
const values = await this.client.getMulti(keys.map((key) => this.buildKey(key)));
for (const key of keys) {
const value = values[this.buildKey(key)];
records[key] = value ? this.deserialize(value.toString()) : null;
}
return records;
}
async has(key) {
return (await this.get(key)) !== null;
}
async put(key, value, ttl) {
return await this.client.set(this.buildKey(key), this.serialize(value), ttl);
}
async add(key, value, ttl) {
return await this.client.add(this.buildKey(key), this.serialize(value), ttl);
}
async putMany(list, ttl) {
const results = [];
for (const [key, value] of Object.entries(list)) {
results.push(this.put(key, value, ttl));
}
return Promise.all(results);
}
async increment(key, value) {
return await this.incrementOrDecrement(key, async () => await this.client.incr(this.buildKey(key), value));
}
async decrement(key, value) {
return await this.incrementOrDecrement(key, async () => await this.client.decr(this.buildKey(key), value));
}
async putManyForever(list) {
const results = [];
for (const [key, value] of Object.entries(list)) {
results.push(this.forever(key, value));
}
return Promise.all(results);
}
async forever(key, value) {
return await this.put(key, value, 0);
}
async forget(key) {
return await this.client.del(this.buildKey(key));
}
async flush() {
return await this.client.flush()[0];
}
async incrementOrDecrement(key, callback) {
try {
if (await this.get(key)) {
return await callback();
}
return false;
}
catch {
return false;
}
}
}
exports.default = Memcached;