Reputation: 488
How can I import this code in module.exports ?
I'm pretty new in node js and in js. I want that this code could be used in other routes
cache = (duration) => {
return (req, res, next) => {
let key = '__express__' + req.originalUrl || req.url
let cachedBody = mcache.get(key)
if (cachedBody) {
res.send(cachedBody)
return
} else {
res.sendResponse = res.send
res.send = (body) => {
mcache.put(key, body, duration * 1000);
res.sendResponse(body)
}
next()
}
}
}
How can I export it?
I was something like :
module.exports = cache = (duration) => {
return (req, res, next) => {
let key = '__express__' + req.originalUrl || req.url
let cachedBody = mcache.get(key)
if (cachedBody) {
res.send(cachedBody)
return
} else {
res.sendResponse = res.send
res.send = (body) => {
mcache.put(key, body, duration * 1000);
res.sendResponse(body)
}
next()
}
}
}
Also I try:
module.export = {
cache: function(duration) {
return (req, res, next) => {
let key = '__express__' + req.originalUrl || req.url
let cachedBody = mcache.get(key)
if (cachedBody) {
res.send(cachedBody)
return
} else {
res.sendResponse = res.send
res.send = (body) => {
mcache.put(key, body, duration * 1000);
res.sendResponse(body)
}
next()
}
}
}
}
But when I try to use it in a get request:
var expCache = require('../../middleware/cache');
router.get('/:sid/fe',expCache.cache(3000),function(req,res) {
It brings:
TypeError: expCache.cache is not a function
Regards
Upvotes: 0
Views: 176
Reputation: 5805
Try
var expCache = require('../../middleware/cache');
router.get('/:sid/fe',expCache(3000),function(req,res) {..
You're exporting your cache function already, not an object containing it (which is how you try to use it for your router).
Upvotes: 1
Reputation: 19772
You need to export an object, if you're expecting to be able to call expCache.cache
:
module.exports = {
cache: // your function
}
However, if you want to keep your exported module as it is, just call it like this instead:
// inside middleware/cache:
// module.exports = cache = (duration) => {
var expCache = require('../../middleware/cache');
// you can call it as just a function
router.get('/:sid/fe', expCache(3000), function(req,res) {
Upvotes: 1