explore-services/services/cache/mecache/cache.js

70 lines
1.8 KiB
JavaScript

'use strict';
let express = require('express');
let app = express();
let mcache = require('memory-cache');
const request = require('superagent');
let cors = require('cors')
app.use(cors())
let cache = (duration) => {
return (req, res, next) => {
let key = '__express__' + req.originalUrl || req.url
let cachedBody = mcache.get(key)
if (cachedBody) {
res.send(JSON.parse(cachedBody))
} else {
res.sendResponse = res.send
res.send = (body) => {
mcache.put(key, body, duration * 1000);
res.sendResponse(body)
};
next();
}
}
};
app.get('/get',cache(20), cors(), (req, res) => {
setTimeout(() => {
const url = (req.query)?req.query.url:null;
if (!url){
res.status(404).send(getResponse(404,"Not Found " +url)) //not found
}else{
request.get(url, function (err, response) {
// res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length");
res.header("Access-Control-Allow-Methods", "GET, OPTIONS");
res.header("Access-Control-Allow-Methods", "GET, OPTIONS");
res.header("Content-Type","application/json");
if (!response && err){
res.status(500).send(getResponse(500,"An error occured for " +url))
return;
}
res.status(response.status).send(response.body);
})
}
})
});
app.use((req, res) => {
res.status(404).send(getResponse(404,"Not Found " +url)); //not found
});
app.listen((process.env.PORT)?process.env.PORT:3000, function () {
console.log(`Example app listening on port ${process.env.PORT}!`)
});
function getResponse(code, message){
var response ={};
response["code"]=code;
response["message"]=message;
return response;
}