updating of redis cache

This commit is contained in:
Tanya Byrne
2020-08-24 12:44:59 +01:00
parent cc6b272442
commit 6a0f294f4d
2 changed files with 22 additions and 8 deletions

View File

@@ -5,7 +5,7 @@
import { RequestHandler } from 'express';
import redis from 'redis';
import asyncHandler from 'express-async-handler';
import NodeCacheService from '../services/authentication';
import CacheService from '../services/authentication';
import { RedisNotFoundException } from '../exceptions';
import env from '../env';
const redisClient = redis.createClient({
@@ -15,18 +15,34 @@ const redisClient = redis.createClient({
password: env.REDIS_PASSWORD,
});
const cache: RequestHandler = asyncHandler(async (req, res, next) => {
const cacheMiddleware: RequestHandler = asyncHandler(async (req, res, next) => {
// make the key of the cache the URL
// need to check that this will work for all endpoints
// node cache service
const key = req.url;
// we have two options here. Redis or node cache
if (env.CACHE_TYPE === 'redis') {
if (!redisClient) {
throw new RedisNotFoundException('Redis client does not exist');
}
redisClient.get(key, (error, resultData) => {
if (error) {
throw new RedisNotFoundException('Error retreiving redis cache');
}
if (resultData) {
res.send(resultData);
}
if (!resultData) {
// set data and then return
redisClient.setex(key, 600, JSON.stringify(res.json));
}
});
}
return next();
});
export default cache;
export default cacheMiddleware;

View File

@@ -1,4 +1,4 @@
/** node cache service.
/** cache service.
* Makes dealing with cache management easier
* in case a new cache is used in future
* sdtTTL is the amount of time a cache should be
@@ -11,7 +11,7 @@
import NodeCache from 'node-cache';
import { InvalidCacheKeyException } from '../exceptions';
export default class NodeCacheService {
export default class CacheService {
apiCache: NodeCache;
constructor(stdTTLSecs: number, checkPeriodSecs: number) {
@@ -32,8 +32,6 @@ export default class NodeCacheService {
this.apiCache.del(keys);
}
// attempt to get the cache based on the key, if it is empty then set it
// am aware there is json interface but not sure but looks like endpoints
// convert string to json
async getCache(key: string, setData: string) {
if (!setData) {
@@ -50,7 +48,7 @@ export default class NodeCacheService {
return setData;
}
// this flushes all data. important!
// this flushes all data. important incase cache gets too full.
async flushCache() {
this.apiCache.flushAll();
}