How to get an objects data inside a function and pass it to a different function in nodejs

Viewed 47

I have this middleware i'm trying to create for my app and i'm wondering on how to get the object's data, inside a separate function, so i can use it on a different function. Thanks in advance.

module.exports = {
    myfunction: function(req, res, next) {
        ...
        body:{
            id:
        }
        ...
    },

    process: function(req, res, next) {
        const id = myfunction.body.id;
        ...
    }
}

Error

    ReferenceError: myfunction is not defined
3 Answers

I'm not sure I completely understand what you are trying to do. But in order to be able to call myfunction from process, you need to declare it outside of the module.exports. For example:

const myfunction = (req, res, next) => {
  return {
    body: {
      id: "id"
    }
  };
};

module.exports = {
  myfunction,
  process: function(req, res, next) {
    const id = myfunction(req, res, next).body.id;
  }
};

You can create an object with those functions and then export that object. The pattern I normally use is:

const self = {
  myfunction: function (req, res, next) {
    let body = {
      id: 1,
    };
    return body
  },

  process: function (req, res, next) {
    const id = self.myfunction().id;
  },
};

module.exports = self;
module.exports = {
myfunction: function(req, res, next) {
    return {
        body: {
            id: 
        }
    }
},

process: function(req, res, next) {
    const id = this.myfunction().body.id;
}
}
Related