Files
ScommettiApp/backend-node/repositories/postgres/users.repository.js
T
2026-04-04 02:40:34 +02:00

87 lines
2.2 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 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;