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

61 lines
1.5 KiB
JavaScript

'use strict'
var express = require('express');
var app = express();
var mcache = require('memory-cache');
const request = require('superagent');
var cors = require('cors')
app.use(cors())
var 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))
return
} else {
res.sendResponse = res.send
res.send = (body) => {
mcache.put(key, body, duration * 1000);
res.sendResponse(body)
}
next()
}
}
}
app.get('/get',cache(10), cors(), (req, res) => {
setTimeout(() => {
const url = (req.query)?req.query.url:null;
if (!url){
res.status(404).send('Not Found'); //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 (err) throw err;
res.send(response.body);
})
}
})
});
app.use((req, res) => {
res.status(404).send('Not Found') //not found
})
app.listen(process.env.PORT, function () {
console.log(`Example app listening on port ${process.env.PORT}!`)
})