Ian Ducao
Ian Ducao

Reputation: 207

How to get an object data from a middleware?

I've been trying to create a checkout on my small business site and I'm trying to use a payment gateway API for it (documentation is subpar), the code below is my attempt to retrieve the paymentMedthod id, but i couldn't figure out on how to get that said id from a middleware funtion without doing this return next(body.data.id) which may cause issue because the middleware would stop and process won't proceed.

Thank you in advance, i know this is kind of dumb question but i really can't use any other API example like stripe in my country. this is the only option i have. Thanks.

e.g.

payment.js

module.exports = {
    paymentMethod: function(req, res, next) {
      
      ...more lines of code here...

      var options = {
        ...more here...
      },
      body: {
          data: {
              id: 1233445,
              ...more here...
          }
      },
      json: true
      };

      request(options, function (error, response, body) {
        if (error) throw new Error(error);

        //console.log(body);
        return next(); //here lies the problem i'm avoiding to use return next(body.data.id) since it will stop the process and the route won't proceed to process what's inside of it.
        
      });
    },
    
     paymentIntent: function(req, res, next) {
         ...more stuff here...
    },
    ...more stuff here...

route.js

const Payment = require('../../config/payment');

//paymentMethod
router.post('/checkout', Payment.paymentIntent, Payment.paymentMethod, (req, res)=>{
    
    //I'm confused on how to get the data coming from the middleware...
    const id = Payment.paymentMethod(body.data.id);
    
    ...more stuff...
  
    var options = {
        ...stuff..
        ...stuff..+id,
        ...stuff...
    };
        
    request(options, function (error, response, body) {
        if (error) throw new Error(error);

        console.log(body); //this should display the id coming from the middle ware
    });      
})

Upvotes: 0

Views: 288

Answers (1)

Duc Nguyen
Duc Nguyen

Reputation: 855

All middlewares share the same req and res objects, so you just have to assign your variable there.

payment.js

module.exports = {
    paymentMethod: function (req, res, next) {

        // ...

        request(options, function (error, response, body) {
            if (error) throw new Error(error);
            req.paymentMethodId = body.data.id; // assign the ID to the req object
            return next();
        });
    },
}

route.js

router.post('/checkout', Payment.paymentIntent, Payment.paymentMethod, (req, res) => {
    const id = Payment.paymentMethod(req.paymentMethodId); // get the ID from the req object

    // ...
})

Calling next(body.data.id) by convention actually triggers error handling, so the request will go to the error handling middleware (if you have one).

Upvotes: 1

Related Questions