Initial commit
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
const { NotFoundError, DatabaseError } = require('../../shared/errors');
|
||||
|
||||
class UsersRepository {
|
||||
constructor({ sequelize }) {
|
||||
this.sequelize = sequelize;
|
||||
this.User = sequelize.models.User;
|
||||
}
|
||||
|
||||
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;
|
||||
Reference in New Issue
Block a user