Files
ScommettiApp/backend-node/repositories/mongo/bets.repository.js
T
2026-03-26 22:46:03 +01:00

103 lines
2.7 KiB
JavaScript

const Bet = require('../../models/bet.model');
const { NotFoundError, DatabaseError } = require('../../shared/errors');
const config = require('../../config');
class BetsRepository {
async findAll(filter = {}, options = {}) {
try {
const { sort = { startDate: -1 }, limit, skip } = options;
let query = Bet.find(filter);
if (sort) query = query.sort(sort);
if (limit) query = query.limit(limit);
if (skip) query = query.skip(skip);
return await query.exec();
} catch (error) {
throw new DatabaseError('Failed to fetch bets', error);
}
}
async findById(id) {
try {
const bet = await Bet.findById(id);
if (!bet) {
throw new NotFoundError('Bet not found');
}
return bet;
} catch (error) {
if (error instanceof NotFoundError) throw error;
if (error.name === 'CastError') {
throw new NotFoundError('Bet not found');
}
throw new DatabaseError(`Failed to fetch bet with id ${id}`, error);
}
}
async findByUser(userId) {
try {
return await Bet.find({ 'participants.user': userId }).sort({ startDate: -1 });
} catch (error) {
throw new DatabaseError(`Failed to fetch bets for user ${userId}`, error);
}
}
async findByGroup(groupId) {
try {
return await Bet.find({ groupId }).sort({ startDate: -1 });
} catch (error) {
throw new DatabaseError(`Failed to fetch bets for group ${groupId}`, error);
}
}
async findPublicBetsExcludingUser(userId) {
try {
return await Bet.find({
isPublic: true,
'participants.user': { $ne: userId },
}).sort({ startDate: -1 });
} catch (error) {
throw new DatabaseError('Failed to fetch public bets', error);
}
}
async create(betData) {
try {
const bet = new Bet({
...betData,
startDate: new Date(),
status: config.BET_STATUS.ACTIVE,
});
return await bet.save();
} catch (error) {
throw new DatabaseError('Failed to create bet', error);
}
}
async update(id, updateData) {
try {
const bet = await this.findById(id);
Object.assign(bet, updateData);
return await bet.save();
} catch (error) {
if (error instanceof NotFoundError) throw error;
throw new DatabaseError(`Failed to update bet with id ${id}`, error);
}
}
async delete(id) {
try {
const result = await Bet.findByIdAndDelete(id);
if (!result) {
throw new NotFoundError('Bet not found');
}
return true;
} catch (error) {
if (error instanceof NotFoundError) throw error;
throw new DatabaseError(`Failed to delete bet with id ${id}`, error);
}
}
}
module.exports = BetsRepository;