Files
ScommettiApp/backend-node/services/groups.service.js
T
2026-03-26 22:46:03 +01:00

77 lines
2.0 KiB
JavaScript

const { ValidationError } = require('../shared/errors');
class GroupsService {
constructor({ groupsRepository, usersRepository }) {
this.groupsRepository = groupsRepository;
this.usersRepository = usersRepository;
}
async getAllGroups() {
return await this.groupsRepository.findAll({
include: [
{
model: this.usersRepository.User,
as: 'members',
through: { attributes: [] },
},
],
});
}
async getGroupById(groupId) {
return await this.groupsRepository.findById(groupId, true);
}
async createGroup(groupData) {
const { name, members } = groupData;
if (!name || name.trim() === '') {
throw new ValidationError('Group name is required');
}
if (!members || !Array.isArray(members) || members.length === 0) {
throw new ValidationError('At least one member is required');
}
for (const userId of members) {
await this.usersRepository.findById(userId);
}
const group = await this.groupsRepository.create({ name });
return await this.groupsRepository.addMembers(group.id, members);
}
async updateGroup(groupId, updateData) {
const { name } = updateData;
if (name && name.trim() === '') {
throw new ValidationError('Group name cannot be empty');
}
return await this.groupsRepository.update(groupId, { name });
}
async deleteGroup(groupId) {
return await this.groupsRepository.delete(groupId);
}
async addMembersToGroup(groupId, userIds) {
if (!userIds || !Array.isArray(userIds) || userIds.length === 0) {
throw new ValidationError('User IDs are required');
}
for (const userId of userIds) {
await this.usersRepository.findById(userId);
}
return await this.groupsRepository.addMembers(groupId, userIds);
}
async removeMemberFromGroup(groupId, userId) {
await this.usersRepository.findById(userId);
return await this.groupsRepository.removeMember(groupId, userId);
}
}
module.exports = GroupsService;