expressjs / express

Fast, unopinionated, minimalist web framework for node.
https://expressjs.com
MIT License
65.2k stars 15.65k forks source link

How to call Express function from another function? #4027

Closed otaviobonder-deel closed 5 years ago

otaviobonder-deel commented 5 years ago

Hi there, I searched the web but I can't find the answer to my question.

I have these express functions:

const token = require("./auth").genToken;
const rp = require("request-promise");
const url = "https://books.zoho.com/api/v3/";

module.exports = {
  async listInvoices(req, res) {
    let response;
    try {
      const full_url = url + "invoices";
      const auth = await token();

      response = await rp({
        url: full_url,
        method: "GET",
        headers: auth,
        json: true
      });

      return res.json(response);
    } catch (error) {
      return res.status(400).send({ error });
    }
  },

  async listBankTransactions(req, res) {
    let response;
    try {
      const full_url = url + "banktransactions";
      const auth = await token();

      response = await rp({
        url: full_url,
        method: "GET",
        headers: auth,
        qs: req.body,
        json: true
      });

      return res.json(response);
    } catch (error) {
      return res.status(400).send({ error });
    }
  },

  async matchTransactions(req, res) {
    let transactions = await module.exports.listBankTransactions(req, res);
    let invoices = await module.exports.listInvoices(req, res);
  }
};

They have different routes, and I can call them. However, I want the matchTransactions function to call listInvoices and listBankTransactions and store their responses in variables, so I can manipulate these data and then return the matchTransactions response.

The way my code is right now, listBankTransactions returns the response instead of storing in transactions constant, and then there is an exception on the listInvoices response, because the response was already returned by listBankTransactions.

What's the best way to achieve what I'm looking for?

Thanks in advance!

wesleytodd commented 5 years ago

I think the simple answer is move the functionality out of your middleware functions and then call them from one or both middleware. For example:

async function listInvoices () {
  // ...
}

app.get('/invoices', await (req, res) => {
  try {
    const invoices = await listInvoices()
    return res.json(invoices);
  } catch (error) {
    return res.status(400).send({ error });
  }
})
app.get('/match', await (req, res) => {
  try {
    const invoices = await listInvoices()
    // ...
  } catch (error) { }
})

If you have further questions I would post on Stack Overflow or in the Express gitter as opposed to here. This is more for bugs and feature development for Express, not support requests. Good luck!