Skip to content

Commit

Permalink
Fix(chat): public and private chat
Browse files Browse the repository at this point in the history
- Add user profile associations on chats
- fix private chat socket
  • Loading branch information
Heisjabo committed Jul 16, 2024
1 parent bfa3e5f commit 541b637
Show file tree
Hide file tree
Showing 6 changed files with 105 additions and 62 deletions.
6 changes: 3 additions & 3 deletions src/config/socketCofing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ let users = new Map<string, string>();
users.set(userId, socket.id)

}

})
socket.on('disconnect', () => {
io.emit('removed');
Expand Down Expand Up @@ -48,8 +47,9 @@ let users = new Map<string, string>();
});

}
export const getSocketIdOfUser =( userId:string ) =>{
return users.get(userId)

export const getSocketIdOfUser =( userId: string ) =>{
return users.get(JSON.stringify(userId))
}

export default socket;
20 changes: 20 additions & 0 deletions src/controllers/userControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,26 @@ export const fetchAllUsers = async (req: Request, res: Response) => {
});
}
};
export const fetchUserById = async (req: Request, res: Response) => {
try {
// @ts-ignore
const userId = req.user?.id;
const user = await userService.getUserById(Number(userId));
if (!user) {
return res.status(404).json({
message: "user not found",
});
} else {
res.status(200).json(user);
}
} catch (error: any) {
console.log(error)
res.status(500).json({
message: "Internal server error",
error: error.message,
});
}
};

export const userLogin = async (req: Request, res: Response) => {
const { email, password } = req.body;
Expand Down
38 changes: 9 additions & 29 deletions src/routes/userRoutes.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,5 @@
import { Router } from "express";
import {
fetchAllUsers,
createUserController,
userLogin,
updatePassword,
tokenVerification,
handleSuccess,
handleFailure,
updateProfileController,
getProfileController,
otpVerification,
updateUserRole,
changeUserAccountStatus,
logout,
sendResetLinkEmail,
resetPasswordController,
verifyUserEmailController,
verifyUserController,
fetchAllsellers,
} from "../controllers/userControllers";
import { fetchAllUsers, createUserController, userLogin, updatePassword, tokenVerification, handleSuccess, handleFailure,updateProfileController, getProfileController, otpVerification,updateUserRole, changeUserAccountStatus, logout, sendResetLinkEmail, resetPasswordController, verifyUserEmailController, verifyUserController, fetchAllsellers, fetchUserById } from "../controllers/userControllers";
import { emailValidation, validateSchema } from "../middlewares/validator";
import { isLoggedIn } from "../middlewares/isLoggedIn";
import { passwordUpdateSchema } from "../schemas/passwordUpdate";
Expand All @@ -38,9 +19,9 @@ import { isPasswordOutOfDate } from "../middlewares/isPasswordOutOfDate";
import { isVerified } from "../middlewares/isVerified";
const userRoutes = Router();

userRoutes.get("/", isLoggedIn, isAdmin, fetchAllUsers);
userRoutes.put("/passwordupdate", isLoggedIn, validateSchema(passwordUpdateSchema), updatePassword);
userRoutes.post("/login", emailValidation, validateSchema(logInSchema), isDisabled, isVerified, userLogin);
userRoutes.get("/",isLoggedIn, fetchAllUsers);
userRoutes.put("/passwordupdate", isLoggedIn, validateSchema(passwordUpdateSchema), updatePassword)
userRoutes.post("/login", emailValidation,validateSchema(logInSchema),isDisabled,isVerified,userLogin);
userRoutes.post("/register", emailValidation, validateSchema(signUpSchema), createUserController);
userRoutes.put("/passwordupdate", isLoggedIn, validateSchema(passwordUpdateSchema), updatePassword);
userRoutes.get("/sellers", fetchAllsellers);
Expand All @@ -67,11 +48,10 @@ userRoutes.get("/auth/google", authenticateUser);
userRoutes.get("/auth/google/callback", callbackFn);
userRoutes.get("/auth/google/success", handleSuccess);
userRoutes.get("/auth/google/failure", handleFailure);
userRoutes.post("/password-reset-link", sendResetLinkEmail);
userRoutes.patch("/reset-password", resetPasswordController);
userRoutes.post("/verify-user-email", verifyUserEmailController);
userRoutes.get("/verify-user", verifyUserController);

userRoutes.get("/me", verifyToken);
userRoutes.post('/password-reset-link', sendResetLinkEmail);
userRoutes.patch('/reset-password', resetPasswordController);
userRoutes.post('/verify-user-email', verifyUserEmailController);
userRoutes.get('/verify-user', verifyUserController);
userRoutes.get("/me", isLoggedIn, fetchUserById);

export default userRoutes;
29 changes: 17 additions & 12 deletions src/sequelize/models/privateChats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,17 +56,22 @@ PrivateChat.init({
modelName:"PrivateChats"
});

User.hasMany(PrivateChat,{
foreignKey: 'userId'
})
PrivateChat.belongsTo(User,{
foreignKey: 'userId'
})
User.hasMany(PrivateChat,{
foreignKey: 'receiverId'
})
PrivateChat.belongsTo(User,{
foreignKey: 'receiverId'
})
User.hasMany(PrivateChat, {
foreignKey: 'userId',
as: 'sentChats'
});
PrivateChat.belongsTo(User, {
foreignKey: 'userId',
as: 'sender'
});

User.hasMany(PrivateChat, {
foreignKey: 'receiverId',
as: 'receivedChats'
});
PrivateChat.belongsTo(User, {
foreignKey: 'receiverId',
as: 'receiver'
});

export default PrivateChat;
58 changes: 40 additions & 18 deletions src/services/privateChat.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import PrivateChat from "../sequelize/models/privateChats";
import Message from "../sequelize/models/messages";
import { findUserById } from "./user.service";
import {Op} from "sequelize";
import Profile from "../sequelize/models/profiles";

export const createPrivateChat = async (userId: number, receiverId: number) => {
try {
Expand Down Expand Up @@ -48,27 +49,48 @@ export const CreatePrivateMessage = async(message:any) => {
}
};

export const getAllUserPrivateChats = async(userId: number) => {
try{
const userChats = await PrivateChat.findAll({
where: {
[Op.or]: [
{userId: userId},
{receiverId: userId}
]},
include: [
export const getAllUserPrivateChats = async (userId: number) => {
try {
const userChats = await PrivateChat.findAll({
where: {
[Op.or]: [
{ userId: userId },
{ receiverId: userId }
]
},
include: [
{
model: Message,
as: 'messages'
},
{
model: User,
as: 'sender',
include: [
{
model: Message,
as: "messages"
}]
model: Profile,
as: 'profile'
}
]
},
{
model: User,
as: 'receiver',
include: [
{
model: Profile,
as: 'profile'
}
]
}
);
return userChats
]
});
return userChats;
} catch (error) {
console.log(error)
// throw new Error(`Error while Fetching your Chats: ${error}`);
}
catch(error){
throw new Error(`Error while Fetching your Chats: ${error}`);
}
};
};

export const getUserToUserPrivateMessages = async (userId: number, receiverId: number) =>{
try{
Expand Down
16 changes: 16 additions & 0 deletions src/services/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export const getAllUsers = async () => {
try {
const users = await User.findAll({
attributes: ['id', 'name', 'username', 'email','lastPasswordUpdateTime', 'roleId', 'createdAt', 'updatedAt','isActive'],
include: [ {model: Profile, as: "profile" }]
});
if (users.length === 0) {
console.log("no user");
Expand All @@ -43,6 +44,21 @@ export const getAllUsers = async () => {
throw new Error(error.message);
}
};
export const getUserById = async (id: number) => {
try {
const user = await User.findByPk(id, {
// attributes: ['id', 'name', 'username', 'email','lastPasswordUpdateTime', 'roleId', 'createdAt', 'updatedAt','isActive'],
include: [ {model: Profile, as: "profile" }]
});
if (!user) {
return null;
}
return user;
} catch (error: any) {
// console.log(error.message);
throw new Error(error);
}
};

export const loggedInUser = async (email: string) => {
try {
Expand Down

0 comments on commit 541b637

Please sign in to comment.