Home > Net >  How to make variables accessible across multiple get requests in express? And is there a better way
How to make variables accessible across multiple get requests in express? And is there a better way

Time:03-28

I have the following get request where I call a bunch of data and pass it through to my EJS view.

router.get('/currentrentals', ensureAuthenticated,  async (req, res) => {

const companies = await Company.getCompanies();
const barges = await Barge.getBarges();
const parishes = await Parish.getParishes();
const states = await State.getStates();
const pickupdropoff = await PickupDropoff.getPickupDropoff();
var notifications = await Notification.getNotifications();
JSON.stringify(barges);
JSON.stringify(companies);
JSON.stringify(parishes);
JSON.stringify(states);
JSON.stringify(pickupdropoff);
JSON.stringify(notifications);
var notifications =  await notifications.sort((a, b) => b.id - a.id).slice(0,3);

res.render('currentrentals', {
    name: req.user.name, companies: companies, barges: barges, parishes: parishes, states: states, pickupdropoff : pickupdropoff, notifications : notifications
});
}
);

Two questions:

  1. I have multiple get requests that requires the same information. Is there a way to make this data available across the entirety of my site, so I don't have to rewrite this for each get path?

  2. Is there a more succinct way to write the existing code I have? Perhaps looping through them or something of the sort? Simply for learning purposes.

The code currently works as-is.

Thanks!

CodePudding user response:

If the data is constant, you can try this:

let data = null;

async function getData() {
  if (!data) {
    data = {
      companies: await Company.getCompanies(),
      barges: await Barge.getBarges();
      parishes: await Parish.getParishes(),
      states: await State.getStates(),
      pickupdropoff: await PickupDropoff.getPickupDropoff(),
      notifications: (await Notification.getNotifications()).sort((a, b) => b.id - a.id).slice(0,3)
    };
  }
  return data;
}

router.get('/currentrentals', ensureAuthenticated, async (req, res) => {
    res.render('currentrentals', { name: req.user.name, ...(await getData()) });
  }
);

// other routes
  • Related