Tengo la siguiente solicitud de obtención en la que llamo a un montón de datos y los paso a mi vista 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 }); } );Dos preguntas:
Tengo varias solicitudes de obtención que requieren la misma información. ¿Hay alguna manera de hacer que estos datos estén disponibles en todo mi sitio, de modo que no tenga que volver a escribir esto para cada ruta de obtención?
¿Hay una forma más sucinta de escribir el código existente que tengo? ¿Quizás recorrerlos o algo por el estilo? Simplemente con fines de aprendizaje.
El código actualmente funciona como está.
¡Gracias!
Si los datos son constantes, puedes probar esto:
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