108 lines
2.6 KiB
JavaScript
108 lines
2.6 KiB
JavaScript
const { Op } = require('sequelize');
|
|
const { NotFoundError, DatabaseError } = require('../../shared/errors');
|
|
|
|
class UsersRepository {
|
|
constructor({ sequelize }) {
|
|
this.sequelize = sequelize;
|
|
this.User = sequelize.models.User;
|
|
}
|
|
|
|
async search(query, excludeUserId) {
|
|
try {
|
|
return await this.User.findAll({
|
|
where: {
|
|
id: { [Op.ne]: excludeUserId },
|
|
[Op.or]: [
|
|
{ name: { [Op.iLike]: `%${query}%` } },
|
|
{ email: { [Op.iLike]: `%${query}%` } },
|
|
],
|
|
},
|
|
limit: 20,
|
|
});
|
|
} catch (error) {
|
|
throw new DatabaseError('Failed to search users', error);
|
|
}
|
|
}
|
|
|
|
async findAll(options = {}) {
|
|
try {
|
|
return await this.User.findAll(options);
|
|
} catch (error) {
|
|
throw new DatabaseError('Failed to fetch users', error);
|
|
}
|
|
}
|
|
|
|
async count() {
|
|
try {
|
|
return await this.User.count();
|
|
} catch (error) {
|
|
throw new DatabaseError('Failed to count users', error);
|
|
}
|
|
}
|
|
|
|
async countWithScoreAbove(score, excludeId) {
|
|
try {
|
|
return await this.User.count({
|
|
where: {
|
|
score: { [Op.gt]: score },
|
|
id: { [Op.ne]: excludeId },
|
|
},
|
|
});
|
|
} catch (error) {
|
|
throw new DatabaseError('Failed to count users above score', error);
|
|
}
|
|
}
|
|
|
|
async findById(id, options = {}) {
|
|
try {
|
|
const user = await this.User.findByPk(id, options);
|
|
if (!user) {
|
|
throw new NotFoundError('User not found');
|
|
}
|
|
return user;
|
|
} catch (error) {
|
|
if (error instanceof NotFoundError) throw error;
|
|
throw new DatabaseError(`Failed to fetch user with id ${id}`, error);
|
|
}
|
|
}
|
|
|
|
async findOne(where, options = {}) {
|
|
try {
|
|
return await this.User.findOne({ where, ...options });
|
|
} catch (error) {
|
|
throw new DatabaseError('Failed to find user', error);
|
|
}
|
|
}
|
|
|
|
async create(userData) {
|
|
try {
|
|
return await this.User.create(userData);
|
|
} catch (error) {
|
|
throw new DatabaseError('Failed to create user', error);
|
|
}
|
|
}
|
|
|
|
async update(id, updateData) {
|
|
try {
|
|
const user = await this.findById(id);
|
|
return await user.update(updateData);
|
|
} catch (error) {
|
|
if (error instanceof NotFoundError) throw error;
|
|
throw new DatabaseError(`Failed to update user with id ${id}`, error);
|
|
}
|
|
}
|
|
|
|
async delete(id) {
|
|
try {
|
|
const user = await this.findById(id);
|
|
await user.destroy();
|
|
return true;
|
|
} catch (error) {
|
|
if (error instanceof NotFoundError) throw error;
|
|
throw new DatabaseError(`Failed to delete user with id ${id}`, error);
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = UsersRepository;
|