如何在 express 中跨多个 get 请求访问变量?有没有更好的编码方式?

How to make variables accessible across multiple get requests in express? And is there a better way to code this?

我有以下获取请求,我在其中调用一堆数据并将其传递到我的 EJS 视图。

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
});
}
);

两个问题:

  1. 我有多个 get 请求需要相同的信息。有没有办法让这些数据在我的整个网站上可用,这样我就不必为每个获取路径重写它?

  2. 有没有更简洁的方法来编写我现有的代码?也许循环遍历它们或类似的东西?仅供学习之用。

代码目前按原样运行。

谢谢!

如果数据不变,可以试试这个:

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