Roshan Shetty
Roshan Shetty

Reputation: 347

How to pass variable to next middleware from gridfs storage

Below is my code where i authenticate if user is admin and then upload a file:

const storage = new GridFsStorage({
  url: process.env.MONGO_URI,
  file: async (req, file) => {
    async function authenticate() {
      const { authorization } = req.headers;
      if (authorization && authorization.startsWith("Bearer")) {
        try {
          const token = authorization.split(" ")[1];
          const decoded = jwt.verify(token, process.env.JWT_SECRET);
          const user = await Auth.findById(decoded.id);
          if (user.admin !== true) {
            throw new Error("Not Authorized") // not working
            // res.status(400).json({message:"Not Authorized"}) //gives error res is not defined
            req.message = "Not Authorized";
          }
        } catch (error) {
          req.message = "Token Error";
        }
      } else {
        req.message = "No Token";
      }
    }
    try{
      await authenticate();
    }catch(err){
      console.log(err);
    }
     return new Promise((resolve, reject) => {
       const fileInfo = {
        filename: id,
        bucketName: "books",
       };
       resolve(fileInfo);
     });
  },
});

const upload = multer({
  storage,
});

module.exports = {
  upload,
};

I get the following error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:370:5)
    at ServerResponse.setHeader (node:_http_outgoing:573:11)
    at ServerResponse.header (D:\Programs\VS Code\Web Development\lmsbackend\node_modules\express\lib\response.js:794:10)
    at ServerResponse.send (D:\Programs\VS Code\Web Development\lmsbackend\node_modules\express\lib\response.js:174:12)
    at ServerResponse.json (D:\Programs\VS Code\Web Development\lmsbackend\node_modules\express\lib\response.js:278:15)
    at errorHandler (D:\Programs\VS Code\Web Development\lmsbackend\middleware\errorMiddleware.js:4:7)
    at Layer.handle_error (D:\Programs\VS Code\Web Development\lmsbackend\node_modules\express\lib\router\layer.js:71:5)
    at trim_prefix (D:\Programs\VS Code\Web Development\lmsbackend\node_modules\express\lib\router\index.js:326:13)
    at D:\Programs\VS Code\Web Development\lmsbackend\node_modules\express\lib\router\index.js:286:9
    at Function.process_params (D:\Programs\VS Code\Web Development\lmsbackend\node_modules\express\lib\router\index.js:346:12)

I understood this error. I could work around this error if i had res available but i do not have res inside my gridfs storage.

I want to authenticate the user and stop execution if user is not admin. But throw new Error() is not working and break is also not accessible.

Also if someone could tell me a technique through which i could pass the error messages to the next middleware which helps me throws them would be helpful.

I tried different ways to pass variable to next middleware as well as stop execution by different ways but i could not. Thanks in advance.

Upvotes: 1

Views: 43

Answers (0)

Related Questions