Files
ScommettiApp/backend-node/repositories/postgres/friendRequests.repository.js
T
2026-04-01 23:49:19 +02:00

98 lines
2.6 KiB
JavaScript

const { Op } = require('sequelize');
const { NotFoundError, DatabaseError } = require('../../shared/errors');
class FriendRequestsRepository {
constructor({ sequelize }) {
this.sequelize = sequelize;
this.FriendRequest = sequelize.models.FriendRequest;
this.User = sequelize.models.User;
}
async findById(id) {
try {
const request = await this.FriendRequest.findByPk(id, {
include: [
{ model: this.User, as: 'fromUser' },
{ model: this.User, as: 'toUser' },
],
});
if (!request) {
throw new NotFoundError('Friend request not found');
}
return request;
} catch (error) {
if (error instanceof NotFoundError) throw error;
throw new DatabaseError(`Failed to fetch friend request with id ${id}`, error);
}
}
async findPendingByUserId(userId) {
try {
return await this.FriendRequest.findAll({
where: {
[Op.or]: [{ toUserId: userId }, { fromUserId: userId }],
status: 'PENDING',
},
include: [
{ model: this.User, as: 'fromUser' },
{ model: this.User, as: 'toUser' },
],
});
} catch (error) {
throw new DatabaseError(`Failed to fetch pending requests for user ${userId}`, error);
}
}
async findExisting(fromUserId, toUserId) {
try {
return await this.FriendRequest.findOne({
where: {
[Op.or]: [
{ fromUserId, toUserId },
{ fromUserId: toUserId, toUserId: fromUserId },
],
status: 'PENDING',
},
});
} catch (error) {
throw new DatabaseError('Failed to check existing friend request', error);
}
}
async create(fromUserId, toUserId) {
try {
const created = await this.FriendRequest.create({
fromUserId,
toUserId,
status: 'PENDING',
});
return await this.findById(created.id);
} catch (error) {
throw new DatabaseError('Failed to create friend request', error);
}
}
async updateStatus(id, status) {
try {
const request = await this.findById(id);
return await request.update({ status });
} catch (error) {
if (error instanceof NotFoundError) throw error;
throw new DatabaseError('Failed to update friend request status', error);
}
}
async delete(id) {
try {
const request = await this.findById(id);
await request.destroy();
return true;
} catch (error) {
if (error instanceof NotFoundError) throw error;
throw new DatabaseError('Failed to delete friend request', error);
}
}
}
module.exports = FriendRequestsRepository;