Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: combine activeUser and User to one collection #642

Merged
merged 2 commits into from
Aug 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions server/controllers/userController.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
/* eslint-disable camelcase */
const UserRouter = require('express').Router();

const { v4: uuidv4 } = require('uuid');
const { ObjectId } = require('mongodb');

const multer = require('multer');
// multer for profile image
const storage = multer.memoryStorage();
const imageUpload = multer({ storage: storage });

const User = require('../models/UserSchema');
const { emailValidator } = require('../utils/helper');
const User = require('../models/UserModel');
const { emailValidator, generateObjectId } = require('../utils/helper');

const {
OK,
Expand All @@ -19,12 +19,21 @@ const {
} = require('../httpStatusCodes.js');

const createUserWithAutoId = async (email) => {
const id = generateObjectId();
// Logic to create a new user with an autogenerated ID
return User.create({ _id: uuidv4(), email });
return User.create({
_id: new ObjectId(id),
email,
loginId: id,
});
};

const createUserWithId = async (email, id) => {
return User.create({ _id: id, email });
return User.create({
_id: new ObjectId(id),
email,
loginId: id,
});
};

const loginUser = async (req, res) => {
Expand Down
2 changes: 1 addition & 1 deletion server/models/ChatModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const ChatSchema = new Schema(
users: [
{
type: Schema.Types.ObjectId,
ref: 'ActiveUser',
ref: 'User',
},
],
messages: [
Expand Down
8 changes: 4 additions & 4 deletions server/models/MessageModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const MessageSchema = new Schema(
sender: {
type: Schema.Types.ObjectId,
required: true,
ref: 'ActiveUser',
ref: 'User',
},
type: {
type: String,
Expand All @@ -35,8 +35,8 @@ const MessageSchema = new Schema(
},
replyTo: {
type: Schema.Types.ObjectId,
ref: 'Message'
}
ref: 'Message',
},
},
{
timestamps: true,
Expand All @@ -53,7 +53,7 @@ const MessageSchema = new Schema(
containsBadword: this.containsBadword,
oldMessages: this.oldMessages,
isRead: this.isRead,
replyTo: this.replyTo?.toString() || null
replyTo: this.replyTo?.toString() || null,
};
},
},
Expand Down
42 changes: 35 additions & 7 deletions server/models/ActiveUserModel.js β†’ server/models/UserModel.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,33 @@
const mongoose = require('mongoose');
const { model, Schema } = mongoose;
const { Schema, model } = mongoose;

const Chat = require('./ChatModel');

const ActiveUserSchema = new Schema(
const UserSchema = new Schema(
{
_id: {
type: String,
},
email: {
type: Schema.Types.Mixed,
default: null,
type: String,
},
gender: {
type: String,
enum: ['Male', 'Female', 'Unknown'],
},
age: {
type: Number,
},
username: {
type: String,
default: 'Anonymous',
},
aboutMe: {
type: String,
},
settings: {
type: Object,
},
profileImage: {
type: String,
},
loginId: {
type: String,
Expand All @@ -31,6 +51,12 @@ const ActiveUserSchema = new Schema(
return {
id: this._id.toString(),
email: this.email || null,
gender: this.gender,
age: this.age,
username: this.username,
aboutMe: this.aboutMe || null,
settings: this.settings || {},
profileImage: this.profileImage || null,
loginId: this.loginId,
emailOrLoginId: this.emailOrLoginId,
socketConnections: [],
Expand All @@ -44,4 +70,6 @@ const ActiveUserSchema = new Schema(
}
);

module.exports = model('ActiveUser', ActiveUserSchema);
UserSchema.index({ loginId: 1 }, { unique: true });

module.exports = model('User', UserSchema);
42 changes: 0 additions & 42 deletions server/models/UserSchema.js

This file was deleted.

8 changes: 7 additions & 1 deletion server/utils/helper.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const crypto = require('crypto');

// Defining separate email validation middleware
const validator = require('validator').default;
const emailValidator = (req, res, next) => {
Expand All @@ -12,7 +14,11 @@ const emailValidator = (req, res, next) => {
}
};

function generateObjectId() {
return crypto.randomBytes(12).toString('hex');
}

module.exports = {
emailValidator,
generateObjectId,
};

77 changes: 48 additions & 29 deletions server/utils/lib.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
const { Socket } = require('socket.io');
const mongoose = require('mongoose');
const CryptoJS = require('crypto-js');
const { ObjectId } = require('mongodb');

const ActiveUser = require('../models/ActiveUserModel');
const ActiveUser = require('../models/UserModel');
const Chat = require('../models/ChatModel');
const Message = require('../models/MessageModel');

const { generateObjectId } = require('./helper');

/**
* @typedef {{
Expand Down Expand Up @@ -127,9 +128,11 @@ function getChatsCount(emailOrLoginId) {
*/
async function delActiveUser(user) {
delete activeUsers[user.emailOrLoginId];
await ActiveUser.deleteOne({
_id: user.id,
});

const userToDelete = await ActiveUser.findById(user.id);
if (!userToDelete.email) {
await ActiveUser.deleteOne({ _id: user.id });
}
}

// This funtion is used for removing user from waiting list
Expand Down Expand Up @@ -192,38 +195,54 @@ async function createChat(users) {

const chatId = _chat._id.toString();

// this shouldn't happen as now new users are added to active users collection instead of users collection.
// this shouldn't happen as now new users are added to active
// users collection instead of users collection.
// find a way to take users from users and fill it in active users.
for (let i = 0; i < users.length; i++) {
const { email, loginId } = users[i];
const user = await ActiveUser.create({
email,
loginId,
currentChat: _chat._id,
});
_chat.users.push(user._id);
try {
for (let i = 0; i < users.length; i++) {
const { email, loginId } = users[i];
let user;
const findUser = await ActiveUser.findOne({ loginId: loginId });
if (findUser) {
user = findUser;
} else {
user = await ActiveUser.create({
email,
loginId,
currentChat: _chat._id,
_id: new ObjectId(generateObjectId()),
});
}
_chat.users.push(user._id);

users[i].id = user._id.toString();
users[i].currentChatId = chatId;
users[i].chatIds.push(chatId);
users[i].id = user._id.toString();
users[i].currentChatId = chatId;
users[i].chatIds.push(chatId);

users[i].socketConnections.map((socket) => {
socket.join(chatId);
});
users[i].socketConnections.map((socket) => {
socket.join(chatId);
});

addActiveUser(users[i]);
addActiveUser(users[i]);
}
} catch (error) {
console.log(`error creating user: ${error}`);
}

const chat = await Chat.create(_chat);
/** @type {Chat} */
const optimizedChat = {
...chat.optimizedVersion,
userIds: users.map((user) => user.emailOrLoginId),
};
try {
const chat = await Chat.create(_chat);
/** @type {Chat} */
const optimizedChat = {
...chat.optimizedVersion,
userIds: users.map((user) => user.emailOrLoginId),
};

chats[chatId] = optimizedChat;
chats[chatId] = optimizedChat;

return optimizedChat;
return optimizedChat;
} catch (error) {
console.log(`error creating chat: ${error}`);
}
}

/**
Expand Down
Loading