2019-08-21 06:16:14 +00:00
|
|
|
import { NextFunction, Request, Response } from 'express';
|
|
|
|
import { HttpException } from '../exceptions/index';
|
|
|
|
import * as redis from 'redis';
|
|
|
|
import { Global } from "../global";
|
|
|
|
import { Duration } from 'moment';
|
|
|
|
|
|
|
|
// connect to Redis
|
2019-08-21 10:03:54 +00:00
|
|
|
// const REDIS_URL = process.env.REDIS_URL;
|
|
|
|
// const client = redis.createClient(REDIS_URL);
|
2019-08-21 06:16:14 +00:00
|
|
|
|
2019-08-21 10:03:54 +00:00
|
|
|
Global.client.on('connect', () => {
|
2019-08-21 06:16:14 +00:00
|
|
|
console.log(`connected to redis`);
|
|
|
|
});
|
2019-08-21 10:03:54 +00:00
|
|
|
Global.client.on('error', err => {
|
2019-08-21 06:16:14 +00:00
|
|
|
console.log(`Error: ${err}`);
|
|
|
|
});
|
|
|
|
|
|
|
|
export function redisMiddleware(
|
|
|
|
duration: any,
|
|
|
|
) {
|
|
|
|
return (request, response, next) => {
|
2019-08-21 10:03:54 +00:00
|
|
|
//console.log(request.originalUrl);
|
2019-08-21 06:16:14 +00:00
|
|
|
// Global.network = request.headers.network;
|
|
|
|
let key = process.env.REDIS_KEY + Global.network + request.originalUrl || request.url
|
2019-08-21 10:03:54 +00:00
|
|
|
Global.client.get(key, function(err, reply){
|
2019-08-21 06:16:14 +00:00
|
|
|
if(reply && duration!=0){
|
2019-08-21 10:03:54 +00:00
|
|
|
//console.log("key : ", key);
|
|
|
|
//console.log("reply : ", reply);
|
|
|
|
//console.log("---------------------------------------------------------------------------------------");
|
|
|
|
//console.log(`enabled`);
|
|
|
|
response.send(JSON.parse(reply));
|
2019-08-21 06:16:14 +00:00
|
|
|
}else{
|
2019-08-21 10:03:54 +00:00
|
|
|
//console.log(`raw`);
|
2019-08-21 06:16:14 +00:00
|
|
|
response.sendResponse = response.send;
|
|
|
|
response.send = (body) => {
|
2019-08-21 10:03:54 +00:00
|
|
|
Global.client.set(key, JSON.stringify(body), 'EX', duration, function(err){
|
2019-08-21 06:16:14 +00:00
|
|
|
//client.set(key, JSON.stringify(body));
|
|
|
|
response.sendResponse(body);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
next();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|