Skip to content

Instantly share code, notes, and snippets.

@marcosrjjunior
Last active January 22, 2023 19:58
Show Gist options
  • Save marcosrjjunior/1a56c087f92fa1573ceaec8136799e2f to your computer and use it in GitHub Desktop.
Save marcosrjjunior/1a56c087f92fa1573ceaec8136799e2f to your computer and use it in GitHub Desktop.
node redis 4.0.4+
// ATTEMPT GET FROM CACHE
if (config.cacheenabled) {
redisInstance = new RedisService();
await redisInstance.connect();
const values = await redisInstance.getValues(name, request.query);
if (values) {
log.info(`[REDIS]: getting inventories from cache`);
await redisInstance.quit();
response.json(values);
return;
}
}
// MAIN REQUEST
if (config.cacheenabled && redisInstance) {
const hash = redisInstance.createHash({
url: name,
payload: request.query,
});
log.info(`[REDIS]: setting inventories to cache`);
await redisInstance.set(hash, cacheInSeconds, inventories);
await redisInstance.quit();
}
import hash from 'object-hash';
import { createClient } from 'redis';
import { config } from '../config';
import { serialize } from '../utils/objectTransformer';
import { log } from '../utils/errors';
export const REDIS_KEY_PREFIX = `PROJECTPREFIX-${config.env?.toLowerCase()}`;
class RedisService {
client: any;
connect = async () => {
this.client = createClient({
url: config.redisconnectionstring,
});
this.client.on('error', (error: any) => {
log.error(`Failed to connect to redis ${error}`);
});
await this.client.connect();
return this.client;
};
quit = async () => {
this.client.quit();
};
createHash = ({
url,
payload,
options,
}: {
url: string;
payload: any;
options?: { query?: any };
}) => {
return options?.query
? `${REDIS_KEY_PREFIX}-${url}?${serialize(options.query)}-${hash(
payload
)}`
: `${REDIS_KEY_PREFIX}-${url}-${hash(payload)}`;
};
get = async ({
url,
payload,
options,
}: {
url: string;
payload: any;
options?: any;
}) => {
const hashedValue = this.createHash({ url, payload, options });
const cacheValue = await this.client.get(hashedValue);
if (typeof cacheValue === 'string') {
return JSON.parse(cacheValue);
}
return undefined;
};
set = (entityHash: string, cacheInSeconds: number, data: any) => {
return this.client.set(entityHash, JSON.stringify(data), {
EX: cacheInSeconds,
NX: true,
});
};
getValues = async (name: string, payload: any) => {
const cachedValues = await this.get({ url: name, payload });
if (!cachedValues) return null;
if (config.isDev) {
log.info(`[REDIS]: getting ${name} from cache`);
}
return cachedValues;
};
}
export { RedisService };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment