Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

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

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!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda