Initial commit
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
// Questo helper necessita del modello User da Sequelize
|
||||
module.exports = (sequelize) => {
|
||||
const { User } = sequelize.models;
|
||||
|
||||
/**
|
||||
* Funzione helper per arricchire i documenti delle scommesse da MongoDB con i dati utente da PostgreSQL.
|
||||
* @param {Array} bets - Un array di documenti di scommesse Mongoose.
|
||||
* @returns {Array} Un array di oggetti scommessa con i dettagli utente popolati.
|
||||
*/
|
||||
const populateBetsWithUsers = async (bets) => {
|
||||
if (!bets || bets.length === 0) return [];
|
||||
|
||||
// Raccoglie tutti gli ID utente unici da tutte le scommesse
|
||||
const userIds = new Set();
|
||||
bets.forEach(bet => {
|
||||
bet.participants.forEach(p => userIds.add(p.user));
|
||||
if (bet.winner) {
|
||||
userIds.add(bet.winner);
|
||||
}
|
||||
});
|
||||
|
||||
if (userIds.size === 0) return bets.map(b => b.toJSON());
|
||||
|
||||
// Recupera tutti gli utenti necessari da PostgreSQL con una singola query
|
||||
const users = await User.findAll({ where: { id: Array.from(userIds) } });
|
||||
const userMap = new Map(users.map(u => [u.id, u.toJSON()]));
|
||||
|
||||
// Unisce i dati utente negli oggetti scommessa
|
||||
return bets.map(bet => {
|
||||
const betJson = bet.toJSON();
|
||||
betJson.participants = betJson.participants.map(p => ({
|
||||
...p,
|
||||
user: userMap.get(p.user) || null
|
||||
}));
|
||||
if (betJson.winner) {
|
||||
betJson.winner = userMap.get(betJson.winner) || null;
|
||||
}
|
||||
return betJson;
|
||||
});
|
||||
};
|
||||
|
||||
return { populateBetsWithUsers };
|
||||
};
|
||||
Reference in New Issue
Block a user