@melchyore/adonis-cache
Version:
Cache package for AdonisJS V5
100 lines (99 loc) • 3.43 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 BaseStore_1 = __importDefault(require("./BaseStore"));
const RedisTaggedCache_1 = __importDefault(require("../RedisTaggedCache"));
const TagSet_1 = __importDefault(require("../TagSet"));
class Redis extends BaseStore_1.default {
constructor(redis, _connection) {
super();
this.redis = redis;
this._connection = _connection;
this.setConnection(_connection);
}
async get(key) {
const value = await this.connection().get(this.buildKey(key));
if (value) {
return this.deserialize(value);
}
return null;
}
async many(keys) {
const records = {};
for (const key of keys) {
records[key] = await this.get(key);
}
return records;
}
async has(key) {
return (await this.connection().exists(this.buildKey(key))) > 0;
}
async put(key, value, ttl) {
return (await this.connection().psetex(this.buildKey(key), ttl, this.serialize(value))) === 'OK';
}
async add(key, value, ttl) {
const lua = 'return redis.call("exists",KEYS[1])<1 and redis.call("psetex",KEYS[1],ARGV[2],ARGV[1])';
return ((await this.connection().eval(lua, 1, this.buildKey(key), this.serialize(value), ttl)) ===
'OK');
}
async putMany(list, ttl) {
const promiseArray = [];
for (const [key, value] of Object.entries(list)) {
promiseArray.push(this.put(key, value, ttl));
}
return Promise.all(promiseArray);
}
async increment(key, value) {
return this.incrementOrDecrement(key, async () => await this.connection().incrby(this.buildKey(key), value));
}
async decrement(key, value) {
return this.incrementOrDecrement(key, async () => await this.connection().decrby(this.buildKey(key), value));
}
async putManyForever(list) {
const promiseArray = [];
for (const [key, value] of Object.entries(list)) {
promiseArray.push(this.forever(key, value));
}
return Promise.all(promiseArray);
}
async forever(key, value) {
try {
await this.connection().set(this.buildKey(key), this.serialize(value));
}
catch {
return false;
}
return true;
}
async forget(key) {
return (await this.connection().del(this.buildKey(key))) > 0;
}
async flush() {
return (await this.connection().flushdb()) === 'OK';
}
tags(names) {
const tagSet = new TagSet_1.default(this, names);
const tagged = new RedisTaggedCache_1.default(this, tagSet, this.prefix);
return tagged;
}
connection() {
return this.redis.connection(this._connection);
}
setConnection(connection) {
this._connection = connection;
}
async incrementOrDecrement(key, callback) {
try {
if (await this.get(key)) {
return await callback();
}
return false;
}
catch {
return false;
}
}
}
exports.default = Redis;