Meisterunner
Meisterunner

Reputation: 262

how to pass a class and call a class's function javascript

I have this JS class

Agent.js

class Agent {
  constructor(agentId) {
    this.agentId = agentId
  }
  getProducts() {
    return arrayOfProducts[]
  }
}

In my login process, I create a new agent:

login.js

function login() {
  //tl;dr
  var agent = new Agent('123')
  req.user = agent
}

Here, I pass the agent to another function

index.js

router.get('/dashboard', (req, res, next) => {
      getUserData.dashboard(req.user, res, next)
    }, (req, res, next) => { //res.render...    });

I don't want to pass around the products from every view so at dashboard I try to get the agent data instead of login.

getUserData.js

var dashboard = (agent, res, next) => {
    console.log(typeof agent) // returns 'object'
    //get products
    var products = agent.getProducts();
next()
}

module.exports = {
dashboard : dashboard 
}

I get an error saying:

getProducts() isn't a function.

How do I pass an agent and get its methods?

Upvotes: 0

Views: 3115

Answers (1)

Eddie D
Eddie D

Reputation: 1120

If you're not using this on the front end you can pass each function as middlware until you're ready to structure you're response. I'd perform validation on each step to ensure the request body has everything needed to perform the operation. I'm not sure why you're calling what looks like another middleware function inside the actual endpoint definition. You can just chain the functions :D

class Agent {
  constructor(agentId) {
    this.agentId = agentId
  }
  getProducts() {
    return arrayOfProducts[]
  }
}

function login(req, res. next) 
{
  //tl;dr
  //Just guessing what the query looks like
  let {_id} = req;
  AgentSchema.findById(_id)
  .then(agent => {
  
    var agent = new Agent(agent._id);
    req.agent = agent;
    next();
  })
  .catch(err => err.status(404).json('Not Found'));
}

function dashboard (req, res, next) => {
    let { agent } = req;
    if(!agent) next(createError(400, 'Agent Not Found on Request Body'));
    //get products
    var products = agent.getProducts();
    //Do some stuff *(Maybe send a response)?
};

//Pass login as middleware
router.get('/dashboard', login, dashboard)

Be advised though, if you're trying to use the method on the front end, JSON does not preserve methods, you'd have to redefine the class on the front and and construct an instance from the response body

Upvotes: 1

Related Questions