Skip to content

Commit

Permalink
Merge pull request #8 from DucHuy2801/chat
Browse files Browse the repository at this point in the history
Chat group
  • Loading branch information
augustus281 authored Apr 27, 2024
2 parents ef8258a + 78b768b commit f8f5812
Show file tree
Hide file tree
Showing 6 changed files with 282 additions and 22 deletions.
44 changes: 43 additions & 1 deletion server/src/controllers/message.controller.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,52 @@
'use strict'

const Message = require("../models/message.model")
const { findGroupByID } = require("../services/group.service")
const { findUserById } = require("../services/user.service")

class MessageController {
createMessage = async(req, res, next) => {

try {
const { content, group_id, user_id } = req.body

const group = await findGroupByID(group_id)
if (!group) return res.status(404).json({ message: "Not found group!" })

const user = await findGroupByID(user_id)
if (!user) return res.status(404).json({ message: "Not found user" })

const newMessage = await Message.create({
content: content,
user_id: user_id,
group_id: group_id
})

if (!newMessage) return res.status(400).json({ message: "Failed to create message!" })
return res.status(200).json({
message: "Create message successfully!",
data: newMessage
})
} catch (error) {
return res.status(500).json({ message: error.message })
}
}

deleteMessage = async (req, res, next) => {
try {
const { groud_id, message_id } = req.params.groud_id;

const group = await findGroupByID(groud_id)
if (!group) return res.status(404).json({ message: "Not found group!" })

const message = await Message.findOne({ where: { message_id: message_id }})
if (!message) return res.status(404).json({ message: "Not found message"})

await message.destroy()

return res.status(200).json({ message: "Delete message successfully!" })
} catch (error) {
return res.status(500).json({ message: error.message })
}
}
}

Expand Down
6 changes: 6 additions & 0 deletions server/src/models/group.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const { DataTypes, Model } = require("sequelize")
const sequelize = require("../database/index")
const Message = require("./message.model")

class Group extends Model {}
Group.init({
Expand All @@ -18,7 +19,12 @@ Group.init({
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0
},
description : {
type: DataTypes.TEXT,
allowNull: true
}
}, { sequelize, modelName: "group" })

Group.hasMany(Message, { foreignKey: "group_id" })
module.exports = Group
182 changes: 164 additions & 18 deletions server/src/postman/BKTravel.json
Original file line number Diff line number Diff line change
Expand Up @@ -1247,16 +1247,6 @@
"value": "7 AM",
"type": "text"
},
{
"key": "departure_place",
"value": "Hồ Chí Minh",
"type": "text"
},
{
"key": "cover_image",
"type": "file",
"src": "postman-cloud:///1eebc125-0093-4d00-89f3-9bedc2c1b433"
},
{
"key": "destination_places",
"value": "Bình Định, Phú Yên",
Expand Down Expand Up @@ -1308,14 +1298,9 @@
"type": "text"
},
{
"key": "image[0]",
"type": "file",
"src": "postman-cloud:///1eede111-1805-4f20-a453-0b91a427b546"
},
{
"key": "image[1]",
"key": "cover_image",
"type": "file",
"src": "postman-cloud:///1eedd801-5670-4710-939b-22ae34334e3b"
"src": "postman-cloud:///1eed137c-d19f-4160-a111-e30af71d0e4d"
}
]
},
Expand Down Expand Up @@ -1407,7 +1392,7 @@
],
"body": {
"mode": "raw",
"raw": "{\r\n \"user_id\": 1,\r\n \"child_quantity\": 2,\r\n \"adult_quantity\": 3,\r\n \"tour_id\": 2,\r\n \"name_customer\": \"Nguyen Duc Huy\",\r\n \"phone_customer\": \"0979957328\",\r\n \"address_customer\": \"Ho Chi Minh City\"\r\n}",
"raw": "{\r\n \"user_id\": 1,\r\n \"child_quantity\": 2,\r\n \"adult_quantity\": 3,\r\n \"tour_id\": 1,\r\n \"name_customer\": \"Nguyen Duc Huy\",\r\n \"phone_customer\": \"0979957328\",\r\n \"address_customer\": \"Ho Chi Minh City\"\r\n}",
"options": {
"raw": {
"language": "json"
Expand Down Expand Up @@ -1468,6 +1453,167 @@
},
"response": []
},
{
"name": "Create group",
"request": {
"method": "POST",
"header": [
{
"key": "Authorization",
"value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJlbWFpbCI6Imh1eS5uZ3V5ZW4yODAxMjAwMkBoY211dC5lZHUudm4iLCJyb2xlX3VzZXIiOiJjdXN0b21lciIsImlhdCI6MTcwNTg1OTEwMSwiZXhwIjoxNzA1ODYwOTAxfQ.CVQhYHm4g_-xFLV-rIezkRoyzOPogEkxm5nzrX6S930",
"type": "text",
"disabled": true
}
],
"body": {
"mode": "raw",
"raw": "{\r\n \"tour_id\": 1,\r\n \"name\": \"Group chat 1\"\r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "http://localhost:8080/api/v1/groups",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"api",
"v1",
"groups"
]
}
},
"response": []
},
{
"name": "Create message",
"request": {
"method": "POST",
"header": [
{
"key": "Authorization",
"value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJlbWFpbCI6Imh1eS5uZ3V5ZW4yODAxMjAwMkBoY211dC5lZHUudm4iLCJyb2xlX3VzZXIiOiJjdXN0b21lciIsImlhdCI6MTcwNTg1OTEwMSwiZXhwIjoxNzA1ODYwOTAxfQ.CVQhYHm4g_-xFLV-rIezkRoyzOPogEkxm5nzrX6S930",
"type": "text",
"disabled": true
}
],
"body": {
"mode": "raw",
"raw": "{\r\n \"group_id\": 1,\r\n \"user_id\": 1,\r\n \"content\": \"Alo\"\r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "http://localhost:8080/api/v1/messages",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"api",
"v1",
"messages"
]
}
},
"response": []
},
{
"name": "Get group by id",
"request": {
"method": "GET",
"header": [
{
"key": "Authorization",
"value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJlbWFpbCI6Imh1eS5uZ3V5ZW4yODAxMjAwMkBoY211dC5lZHUudm4iLCJyb2xlX3VzZXIiOiJjdXN0b21lciIsImlhdCI6MTcwNTg1OTEwMSwiZXhwIjoxNzA1ODYwOTAxfQ.CVQhYHm4g_-xFLV-rIezkRoyzOPogEkxm5nzrX6S930",
"type": "text",
"disabled": true
}
],
"url": {
"raw": "http://localhost:8080/api/v1/groups/1",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"api",
"v1",
"groups",
"1"
]
}
},
"response": []
},
{
"name": "Get group by tour id",
"request": {
"method": "GET",
"header": [
{
"key": "Authorization",
"value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJlbWFpbCI6Imh1eS5uZ3V5ZW4yODAxMjAwMkBoY211dC5lZHUudm4iLCJyb2xlX3VzZXIiOiJjdXN0b21lciIsImlhdCI6MTcwNTg1OTEwMSwiZXhwIjoxNzA1ODYwOTAxfQ.CVQhYHm4g_-xFLV-rIezkRoyzOPogEkxm5nzrX6S930",
"type": "text",
"disabled": true
}
],
"url": {
"raw": "http://localhost:8080/api/v1/groups/tours/1",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"api",
"v1",
"groups",
"tours",
"1"
]
}
},
"response": []
},
{
"name": "Get all groups",
"request": {
"method": "GET",
"header": [
{
"key": "Authorization",
"value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJlbWFpbCI6Imh1eS5uZ3V5ZW4yODAxMjAwMkBoY211dC5lZHUudm4iLCJyb2xlX3VzZXIiOiJjdXN0b21lciIsImlhdCI6MTcwNTg1OTEwMSwiZXhwIjoxNzA1ODYwOTAxfQ.CVQhYHm4g_-xFLV-rIezkRoyzOPogEkxm5nzrX6S930",
"type": "text",
"disabled": true
}
],
"url": {
"raw": "http://localhost:8080/api/v1/groups",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"api",
"v1",
"groups"
]
}
},
"response": []
},
{
"name": "Get pending order by user",
"request": {
Expand Down
1 change: 1 addition & 0 deletions server/src/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@ router.use('/api/v1/voucher', require("./voucher"))
router.use('/api/v1/review', require("./review"))
router.use('/api/v1/order', require("./order"))
router.use('/api/v1/groups', require("./group"))
router.use('/api/v1/messages', require("./message"))

module.exports = router
11 changes: 11 additions & 0 deletions server/src/routes/message/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict'

const express = require("express")
const router = express.Router()
const { asyncHandler } = require('../../auth/checkAuth')
const messageController = require("../../controllers/message.controller")

router.post("/", asyncHandler(messageController.createMessage))
router.delete("/", asyncHandler(messageController.deleteMessage))

module.exports = router
60 changes: 57 additions & 3 deletions server/src/socket/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,63 @@
const io = require("socket.io")(8900, {
const app = require("../app");
const Group = require("../models/group.model")
const GroupUser = require("../models/group_member.model");

const server = require("http").createServer(app)
const io = require("socket.io")(server, {
cors: {
origin: `http://localhost:${process.env.CLIENT_PORT}`
origin: 'http://localhost:3000',
METHODS: ["POST", "GET"],
Credential: true
}
})

// using socket
const onlineUsers = [];
io.on("connection", (socket) => {
console.log("A user connected")
console.log("A connection has been made");
// store in users array in online
socket.on("online", (userID) => {
onlineUsers.push({ userId: userID, socketId: socket.id })
})

// add member to group
socket.on("add ember", async (userID) => {
const target = onlineUsers.find((user) => user.userId == userID)

if (target) {
const groupIDs = await GroupUser.findAll({
attributes: ["group_id"],
where: { user_id: userID }
})

const allGroups = [];
for (let i = 0; i < groupIDs.length; i++) {
allGroups.push(groupIDs[i].group_id);
}

const groups = await Group.findAll({
attributes: ["group_id", "name", "description"],
where: { group_id: allGroups },
});

console.log(target.socketId);
io.to(target.socketId).emit("groupData", groups);
}
})

// make user join a room
socket.on("join", function (room) {
socket.join(room);
});

// broadcast the message to a room
socket.on("send message", (msg, room) => {
io.in(room).emit("room message", msg);
});

// on disconnection
socket.on("disconnect", () => {
console.log("A disconnection has been made");
});

})

0 comments on commit f8f5812

Please sign in to comment.