79 lines
2.0 KiB
JavaScript
79 lines
2.0 KiB
JavaScript
const { NotFoundError, DatabaseError } = require('../../shared/errors');
|
|
const { Op } = require('sequelize');
|
|
|
|
class FriendshipsRepository {
|
|
constructor({ sequelize }) {
|
|
this.sequelize = sequelize;
|
|
this.Friendship = sequelize.models.Friendship;
|
|
this.User = sequelize.models.User;
|
|
}
|
|
|
|
async findByUserId(userId) {
|
|
try {
|
|
const friendships = await this.Friendship.findAll({
|
|
where: {
|
|
[Op.or]: [{ user1Id: userId }, { user2Id: userId }],
|
|
},
|
|
include: [
|
|
{ model: this.User, as: 'user1' },
|
|
{ model: this.User, as: 'user2' },
|
|
],
|
|
});
|
|
|
|
return friendships.map((friendship) => {
|
|
const friend =
|
|
friendship.user1.id === userId ? friendship.user2 : friendship.user1;
|
|
return friend;
|
|
});
|
|
} catch (error) {
|
|
throw new DatabaseError(`Failed to fetch friendships for user ${userId}`, error);
|
|
}
|
|
}
|
|
|
|
async exists(user1Id, user2Id) {
|
|
try {
|
|
const minId = Math.min(user1Id, user2Id);
|
|
const maxId = Math.max(user1Id, user2Id);
|
|
|
|
const friendship = await this.Friendship.findOne({
|
|
where: { user1Id: minId, user2Id: maxId },
|
|
});
|
|
|
|
return !!friendship;
|
|
} catch (error) {
|
|
throw new DatabaseError('Failed to check friendship existence', error);
|
|
}
|
|
}
|
|
|
|
async create(user1Id, user2Id) {
|
|
try {
|
|
const minId = Math.min(user1Id, user2Id);
|
|
const maxId = Math.max(user1Id, user2Id);
|
|
|
|
return await this.Friendship.create({
|
|
user1Id: minId,
|
|
user2Id: maxId,
|
|
});
|
|
} catch (error) {
|
|
throw new DatabaseError('Failed to create friendship', error);
|
|
}
|
|
}
|
|
|
|
async delete(user1Id, user2Id) {
|
|
try {
|
|
const minId = Math.min(user1Id, user2Id);
|
|
const maxId = Math.max(user1Id, user2Id);
|
|
|
|
const result = await this.Friendship.destroy({
|
|
where: { user1Id: minId, user2Id: maxId },
|
|
});
|
|
|
|
return result > 0;
|
|
} catch (error) {
|
|
throw new DatabaseError('Failed to delete friendship', error);
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = FriendshipsRepository;
|