@graphql-mesh/cache-redis
Version:
80 lines (75 loc) • 2.81 kB
JavaScript
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
const Redis = _interopDefault(require('ioredis'));
const stringInterpolation = require('@graphql-mesh/string-interpolation');
const crossHelpers = require('@graphql-mesh/cross-helpers');
const RedisMock = _interopDefault(require('ioredis-mock'));
function interpolateStrWithEnv(str) {
return stringInterpolation.stringInterpolator.parse(str, { env: crossHelpers.process.env });
}
class RedisCache {
constructor(options) {
if (options.url) {
const redisUrl = new URL(interpolateStrWithEnv(options.url));
redisUrl.searchParams.set('lazyConnect', 'true');
redisUrl.searchParams.set('enableAutoPipelining', 'true');
redisUrl.searchParams.set('enableOfflineQueue', 'true');
if (!['redis:', 'rediss:'].includes(redisUrl.protocol)) {
throw new Error('Redis URL must use either redis:// or rediss://');
}
this.client = new Redis(redisUrl.toString());
}
else {
const parsedHost = interpolateStrWithEnv(options.host);
const parsedPort = interpolateStrWithEnv(options.port);
const parsedPassword = interpolateStrWithEnv(options.password);
if (parsedHost) {
this.client = new Redis({
host: parsedHost,
port: parseInt(parsedPort),
password: parsedPassword,
lazyConnect: true,
enableAutoPipelining: true,
enableOfflineQueue: true,
});
}
else {
this.client = new RedisMock();
}
}
const id = options.pubsub.subscribe('destroy', () => {
this.client.disconnect(false);
options.pubsub.unsubscribe(id);
});
}
async set(key, value, options) {
const stringifiedValue = JSON.stringify(value);
if (options === null || options === void 0 ? void 0 : options.ttl) {
await this.client.set(key, stringifiedValue, 'EX', options.ttl);
}
else {
await this.client.set(key, stringifiedValue);
}
}
async get(key) {
const reply = await this.client.get(key);
if (reply !== null) {
const value = JSON.parse(reply);
return value;
}
return undefined;
}
async getKeysByPrefix(prefix) {
return this.client.keys(`${prefix}*`);
}
async delete(key) {
try {
await this.client.del(key);
return true;
}
catch (e) {
return false;
}
}
}
module.exports = RedisCache;
;