@squareboat/nest-cache
Version:
The cache package for your NestJS Applications
91 lines (90 loc) • 3.17 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.RedisDriver = void 0;
const ioredis_1 = require("ioredis");
class RedisDriver {
constructor(options) {
this.options = options;
this.client = new ioredis_1.default(Object.assign({}, options));
}
get(key) {
return __awaiter(this, void 0, void 0, function* () {
const value = yield this.client.get(`${this.options.prefix}:::${key}`);
if (!value)
return null;
try {
return JSON.parse(value);
}
catch (e) {
return value;
}
});
}
set(key, value, ttlInSec) {
return __awaiter(this, void 0, void 0, function* () {
const redisKey = `${this.options.prefix}:::${key}`;
if (ttlInSec) {
yield this.client.set(redisKey, JSON.stringify(value), "EX", ttlInSec);
return;
}
yield this.client.set(redisKey, JSON.stringify(value));
});
}
has(key) {
return __awaiter(this, void 0, void 0, function* () {
const num = yield this.client.exists(`${this.options.prefix}:::${key}`);
return !!num;
});
}
remember(key, cb, ttlInSec) {
return __awaiter(this, void 0, void 0, function* () {
const exists = yield this.has(key);
if (exists)
return this.get(key);
try {
const response = yield cb();
yield this.set(key, response, ttlInSec);
return response;
}
catch (e) {
throw e;
}
});
}
rememberForever(key, cb) {
return __awaiter(this, void 0, void 0, function* () {
const exists = yield this.has(key);
if (exists)
return this.get(key);
try {
const response = yield cb();
yield this.set(key, response);
return response;
}
catch (e) {
throw e;
}
});
}
forget(key) {
return __awaiter(this, void 0, void 0, function* () {
yield this.client.del(this.storeKey(key));
});
}
storeKey(key) {
return `${this.options.prefix}:::${key}`;
}
getClient() {
return this.client;
}
}
exports.RedisDriver = RedisDriver;