Alwaysblue
Alwaysblue

Reputation: 11830

Exporting a function in NodeJS

I have mostly worked with React so I am not that fimilar with require and export of NodeJS

But anyway, I was trying to create a middle ware by doing something like this

const { clearHash } = require("../services/cache.js")

const clearCache = async (req, res, next) => {
    await next();
    clearHash(req.user.id)
} 

module.exports = clearCache

Which I tend to import by doing something like this

const { clearCache } = require("../middlewares/cache.js")

Now, Usually what I used to do (by reading on interned) was

module.exports = (req, res, next) => {
  if (!req.user) {
    return res.status(401).send({ error: 'You must log in!' });
  }
  next();
};

Which works, but then again i though about playing around and realised that my first snippet of code doesn't seem to be working when I do something like this

app.post('/api/blogs', requireLogin, clearCache, async (req, res) => {

Can someone help me comprehend what could be the reason for the same?

Upvotes: 0

Views: 39

Answers (1)

itsundefined
itsundefined

Reputation: 1450

To be able to use the object destructuring as const { clearCache } you need to change the module.exports from module.exports = clearCache to module.exports = { clearCache }

Upvotes: 1

Related Questions