Currently, my app only allows conversations between two users. I would like to allow conversations with groups of 3 or more users. The number of users will be established whenever a user creates a group conversation and adds other users. Therefore, I can't hardcore a fixed number of Conversation belonging to User associations.
Conversation model:
const { Op } = require("sequelize");
const db = require("../db");
const Conversation = db.define("conversation", {});
// find conversation given two user Ids
Conversation.findConversation = async function (user1Id, user2Id) {
const conversation = await Conversation.findOne({
where: {
user1Id: {
[Op.or]: [user1Id, user2Id]
},
user2Id: {
[Op.or]: [user1Id, user2Id]
}
}
});
// return conversation or null if it doesn't exist
return conversation;
};
Associations:
const Conversation = require("./conversation");
const User = require("./user");
const Message = require("./message");
// associations
User.hasMany(Conversation);
Conversation.belongsTo(User, { as: "user1" });
Conversation.belongsTo(User, { as: "user2" });
Message.belongsTo(Conversation);
Conversation.hasMany(Message);