Files

52 lines
1.5 KiB
JavaScript

const { ValidationError } = require('../shared/errors');
class UsersService {
constructor({ usersRepository }) {
this.usersRepository = usersRepository;
}
async getAllUsers() {
return await this.usersRepository.findAll();
}
async getUserById(id) {
return await this.usersRepository.findById(id);
}
async getCurrentUserWithRank(id) {
const user = await this.usersRepository.findById(id);
const userJson = user.toJSON ? user.toJSON() : { ...user };
const totalUsers = await this.usersRepository.count();
const usersAbove = await this.usersRepository.countWithScoreAbove(userJson.score, id);
const rankPercentile = totalUsers > 1
? Math.max(1, Math.round((usersAbove / totalUsers) * 100))
: 1;
return { ...userJson, rankPercentile };
}
async searchUsers(query, excludeUserId) {
return await this.usersRepository.search(query, excludeUserId);
}
async updateUserProfile(id, updateData) {
const { name, email, avatarUrl } = updateData;
if (name && name.trim() === '') {
throw new ValidationError('Name cannot be empty');
}
if (email && email.trim() === '') {
throw new ValidationError('Email cannot be empty');
}
const dataToUpdate = {};
if (name !== undefined) dataToUpdate.name = name;
if (email !== undefined) dataToUpdate.email = email;
if (avatarUrl !== undefined) dataToUpdate.avatarUrl = avatarUrl;
return await this.usersRepository.update(id, dataToUpdate);
}
}
module.exports = UsersService;