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

[finishes #187942837] fixing bug in cart controller and chat model #96

Merged
merged 1 commit into from
Jul 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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"express": "^4.19.2",
"express-winston": "^4.2.0",
"glob": "^10.3.12",
"jest-mock-req-res": "^1.0.2",
"jsonwebtoken": "^9.0.2",
"mailgen": "^2.0.28",
"multer": "^1.4.5-lts.1",
Expand Down
7 changes: 3 additions & 4 deletions src/chatSetup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ export const findId = (socket: CustomSocket) => {
};

interface Message {
socketId: string;
content: string;
msgData: string;
}
Expand All @@ -39,14 +38,14 @@ const sentMessage = async (socket: CustomSocket, data: Message, io: Server) => {
const senderId = socket.userId;
if (senderId) {
try {
const { content, socketId } = data;
const { content } = data;
console.log('--------------messages are here,', data);
const { firstName } = await getUserNames(socket.userId as string);

const chat = await Chat.create({ senderId, socketId, content });
const chat = await Chat.create({ senderId, content });

io.emit('returnMessage', {
senderId: chat.dataValues.senderId,
socketId: chat.dataValues.socketId,
content: chat.dataValues.content,
senderName: firstName,
readStatus: chat.dataValues.readStatus,
Expand Down
37 changes: 35 additions & 2 deletions src/controllers/cartController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Size } from '../database/models/Size';
import CartsProducts from '../database/models/cartsProducts';
import { validateFields } from '../validations';
import { Transaction } from 'sequelize';
import { time } from 'console';
const addCartItem = async (req: Request, res: Response): Promise<void> => {
const { productId, sizeId, quantity } = req.body;
const { id: userId } = req.user as User;
Expand Down Expand Up @@ -120,7 +121,6 @@ const updateCartItem = async (req: Request, res: Response): Promise<void> => {
};

//getting items of a cart

const getCartItems = async (req: Request, res: Response): Promise<void> => {
const { id: userId } = req.user as User;

Expand Down Expand Up @@ -168,9 +168,11 @@ const getCartItems = async (req: Request, res: Response): Promise<void> => {
transaction,
}),
quantity: item.quantity,
timeStamps: (item as any).createdAt,
};
})
);

if ((await allProducts).length < 1) {
res.status(404).json({ ok: false, message: 'No Product in the Cart' });
return;
Expand All @@ -185,6 +187,7 @@ const getCartItems = async (req: Request, res: Response): Promise<void> => {
sellerId,
image: images[0],
quantity: item.quantity,
createdAt: item.timeStamps,
};
});
await transaction.commit();
Expand Down Expand Up @@ -225,4 +228,34 @@ const clearCart = async (req: Request, res: Response): Promise<void> => {
}
};

export { addCartItem, updateCartItem, getCartItems, clearCart };
// controller to delete cart item
const deleteCartItem = async (req: Request, res: Response): Promise<void> => {
const { productId, sizeId } = req.body;
const { id: userId } = req.user as User;

const transaction = await sequelize.transaction();
try {
const cartItem: Cart | null = await Cart.findOne({
where: { userId },
transaction,
});

if (cartItem === null) {
res.status(404).json({ ok: false, message: 'Cart not found' });
return;
}

await CartsProducts.destroy({
where: { cartId: cartItem.id, productId, sizeId },
transaction,
});

await transaction.commit();
res.status(200).json({ ok: true, message: 'Cart item deleted successfully' });
} catch (error) {
await transaction.rollback();
logger.error(error);
sendInternalErrorResponse(res, error);
}
};
export { addCartItem, updateCartItem, getCartItems, clearCart, deleteCartItem };
2 changes: 1 addition & 1 deletion src/controllers/chatController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const chats = async (req: Request, res: Response) => {
model: User,
attributes: ['firstName', 'lastName', 'photoUrl'],
},
attributes: ['id', 'senderId', 'socketId', 'content', 'updatedAt'],
attributes: ['id', 'senderId', 'content', 'updatedAt'],
});

return res.status(200).json({ ok: true, chat });
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/userController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ export const editUser = async (req: Request, res: Response) => {
photoUrl: updatedFields.photoUrl,
};

res.status(201).json({ ok: true, message: userResponse });
res.status(201).json({ ok: true, data: userResponse });
} catch (error) {
logger.error('Error Edit User Role: ', error);
sendInternalErrorResponse(res, error);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface) {
await queryInterface.removeColumn('Chats', 'socketId');
},

async down(queryInterface, Sequelize) {
await queryInterface.addColumn('Chats', 'socketId', {
type: Sequelize.STRING,
allowNull: true,
});
},
};
8 changes: 2 additions & 6 deletions src/database/models/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ interface ChatAttr {
id: string;
senderId: string;
content: string;
socketId: string;
readStatus?: boolean;
createdAt?: Date | null;
updatedAt?: Date | null;
Expand All @@ -18,7 +17,6 @@ class Chat extends Model<ChatAttr, ChatCreationAttr> implements ChatAttr {
public id!: string;
public senderId!: string;
public content!: string;
public socketId!: string;
public readStatus!: boolean;
public readonly createdAt: Date | undefined;
public readonly updatedAt: Date | undefined;
Expand All @@ -45,10 +43,7 @@ Chat.init(
type: DataTypes.STRING,
allowNull: false,
},
socketId: {
type: DataTypes.STRING,
allowNull: false,
},

readStatus: {
type: DataTypes.BOOLEAN,
allowNull: true,
Expand All @@ -66,3 +61,4 @@ Chat.init(
Chat.belongsTo(User, { foreignKey: 'senderId' });

export default Chat;
// sequelize migration to remove the column socketId from the Chats table
4 changes: 2 additions & 2 deletions src/routes/cartRoute.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import express from 'express';

import { addCartItem, updateCartItem, getCartItems, clearCart } from '../controllers/cartController';
import { addCartItem, updateCartItem, getCartItems, clearCart, deleteCartItem } from '../controllers/cartController';

import { checkUserRoles, isAuthenticated } from '../middlewares/authMiddlewares';

Expand All @@ -12,5 +12,5 @@ cartRouter
.post([isAuthenticated, checkUserRoles('buyer')], addCartItem)
.delete([isAuthenticated, checkUserRoles('buyer')], clearCart);
cartRouter.route('/:id').patch([isAuthenticated, checkUserRoles('buyer')], updateCartItem);

cartRouter.route('/delete').delete([isAuthenticated, checkUserRoles('buyer')], deleteCartItem);
export default cartRouter;
Loading