47 lines
1.7 KiB
JavaScript
47 lines
1.7 KiB
JavaScript
// eslint-disable-next-line import/no-import-module-exports
|
|
import { DataTypes } from 'sequelize';
|
|
|
|
module.exports = sequelize => {
|
|
const { User, Group, FriendRequest, Friendship } = sequelize.models;
|
|
|
|
// User <-> Group: Many-to-Many
|
|
// Il modello dichiara esplicitamente la colonna id per evitare che sync() la cerchi
|
|
// sulla tabella UserGroups senza trovarla (causando errori su RETURNING "id").
|
|
const UserGroup = sequelize.define(
|
|
'UserGroup',
|
|
{
|
|
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
|
userId: { type: DataTypes.INTEGER, allowNull: false },
|
|
groupId: { type: DataTypes.INTEGER, allowNull: false },
|
|
},
|
|
{ timestamps: false }
|
|
);
|
|
User.belongsToMany(Group, { through: UserGroup, foreignKey: 'userId', otherKey: 'groupId' });
|
|
Group.belongsToMany(User, {
|
|
through: UserGroup,
|
|
as: 'members',
|
|
foreignKey: 'groupId',
|
|
otherKey: 'userId',
|
|
});
|
|
|
|
// Friendship is a direct link between two users.
|
|
// user1Id will always be less than user2Id to ensure uniqueness.
|
|
Friendship.belongsTo(User, { as: 'user1', foreignKey: 'user1Id' });
|
|
Friendship.belongsTo(User, { as: 'user2', foreignKey: 'user2Id' });
|
|
|
|
// User <-> FriendRequest: One-to-Many
|
|
// A User can send many friend requests and receive many friend requests.
|
|
User.hasMany(FriendRequest, {
|
|
as: 'sentRequests',
|
|
foreignKey: 'fromUserId',
|
|
onDelete: 'CASCADE',
|
|
});
|
|
User.hasMany(FriendRequest, {
|
|
as: 'receivedRequests',
|
|
foreignKey: 'toUserId',
|
|
onDelete: 'CASCADE',
|
|
});
|
|
FriendRequest.belongsTo(User, { as: 'fromUser', foreignKey: 'fromUserId' });
|
|
FriendRequest.belongsTo(User, { as: 'toUser', foreignKey: 'toUserId' });
|
|
};
|