Commit 1d85ac6b authored by 健杭 徐's avatar 健杭 徐
Browse files

get method

parent 6152d12b
...@@ -142,6 +142,10 @@ func AddMessage(c *gin.Context) { ...@@ -142,6 +142,10 @@ func AddMessage(c *gin.Context) {
"INSERT INTO messages (roomId, profile_id, sender, content, timestamp) VALUES ($1, $2, NOW()) RETURNING message_id", "INSERT INTO messages (roomId, profile_id, sender, content, timestamp) VALUES ($1, $2, NOW()) RETURNING message_id",
message.RoomId, message.Profile_id, message.Sender, message.Content, message.RoomId, message.Profile_id, message.Sender, message.Content,
).Scan(&messageId) ).Scan(&messageId)
_, err = db.Exec(
"UPDATE rooms SET last_sender = $1, last_content = $2, last_time = NOW() WHERE room_id = $3",
message.Sender, message.Content, message.RoomId,
)
if err != nil { if err != nil {
c.JSON(500, Response{Code: 500, Msg: "Failed to add message", Data: nil}) c.JSON(500, Response{Code: 500, Msg: "Failed to add message", Data: nil})
return return
...@@ -157,7 +161,34 @@ func AddMessage(c *gin.Context) { ...@@ -157,7 +161,34 @@ func AddMessage(c *gin.Context) {
} }
func GetMessageList(c *gin.Context) { func GetMessageList(c *gin.Context) {
// 处理获取消息列表的逻辑 roomId := c.Query("roomId")
if roomId == "" {
c.JSON(400, Response{Code: 400, Msg: "Room ID is required", Data: nil})
return
}
rows, err := db.Query("SELECT profile_id, sender, content, time FROM messages WHERE room_id = $1 ORDER BY time ASC", roomId)
if err != nil {
c.JSON(500, Response{Code: 500, Msg: "Failed to retrieve messages", Data: nil})
return
}
defer rows.Close()
var messages []Message
for rows.Next() {
var msg Message
if err := rows.Scan(&msg.Profile_id, &msg.Sender, &msg.Content, &msg.Timestamp); err != nil {
c.JSON(500, Response{Code: 500, Msg: "Failed to scan message", Data: nil})
return
}
messages = append(messages, msg)
}
c.JSON(200, Response{
Code: 0,
Msg: "Messages retrieved successfully",
Data: messages,
})
} }
func RoomMessageUpdate(c *gin.Context) { func RoomMessageUpdate(c *gin.Context) {
...@@ -166,20 +197,22 @@ func RoomMessageUpdate(c *gin.Context) { ...@@ -166,20 +197,22 @@ func RoomMessageUpdate(c *gin.Context) {
func createTable() { func createTable() {
query := ` query := `
CREATE TABLE IF NOT EXISTS rooms (
room_id SERIAL PRIMARY KEY,
room_name VARCHAR(100) NOT NULL UNIQUE,
last_sender VARCHAR(100),
last_content TEXT,
last_time TIMESTAMP
);
CREATE TABLE IF NOT EXISTS messages ( CREATE TABLE IF NOT EXISTS messages (
message_id SERIAL PRIMARY KEY, message_id SERIAL PRIMARY KEY,
room_id INT NOT NULL, room_id INT NOT NULL,
profile_id INT NOT NULL, profile_id INT NOT NULL,
sender VARCHAR(100) NOT NULL, sender VARCHAR(100) NOT NULL,
content TEXT NOT NULL, content TEXT NOT NULL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP "time" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
); FOREIGN KEY (room_id) REFERENCES rooms(room_id)
CREATE TABLE IF NOT EXISTS rooms (
room_id SERIAL PRIMARY KEY,
room_name VARCHAR(100) NOT NULL
LAST_MESSAGE TEXT,
LAST_MESSAGE_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP
); );
` `
_, err := db.Exec(query) _, err := db.Exec(query)
......
'use client'; 'use client';
import "./ChatRoom.css"; import "./ChatRoom.css";
import React, { useState } from "react"; import React, { useEffect, useState } from "react";
// profile // profile
const Profile = [ 'https://pic4.zhimg.com/v2-c5a0d0d57c1a85c6db56e918707f54a3_r.jpg', const Profile = [ 'https://pic4.zhimg.com/v2-c5a0d0d57c1a85c6db56e918707f54a3_r.jpg',
...@@ -46,7 +46,7 @@ if (RoomName.length > 0) { ...@@ -46,7 +46,7 @@ if (RoomName.length > 0) {
RoomRightNow.roomName = RoomName[0].roomName; RoomRightNow.roomName = RoomName[0].roomName;
} }
function RoomEntry () { function RoomEntry ({rooms, onRoomClick} : {rooms: RoomEntryProps[], onRoomClick: (roomId: number, roomName: string) => void}) {
return ( return (
<div className="chat-room-nav"> <div className="chat-room-nav">
<div className="sidebar-action"> <div className="sidebar-action">
...@@ -58,8 +58,8 @@ function RoomEntry () { ...@@ -58,8 +58,8 @@ function RoomEntry () {
</div> </div>
<div className="chat-list"> <div className="chat-list">
{RoomName.map((room) => ( {rooms.map((room) => (
<div className="chat-item" key={room.roomId} onClick={() => handleRoomClick(room.roomId, room.roomName)}> <div className="chat-item" key={room.roomId} onClick={() => onRoomClick(room.roomId, room.roomName)}>
<img src={RoomProfile} alt="Avatar" className="avatar" /> <img src={RoomProfile} alt="Avatar" className="avatar" />
<div className="chat-info"> <div className="chat-info">
<h3>{room.roomName}</h3> <h3>{room.roomName}</h3>
...@@ -83,11 +83,7 @@ function handleRoomClick(roomId: number, roomName: string) { ...@@ -83,11 +83,7 @@ function handleRoomClick(roomId: number, roomName: string) {
} }
function InputRoomNameArea() { function InputRoomNameArea() {
const [roomId, setRoomId] = useState(0); // This component is used to input the new room name
function handleRoomIdChange() {
setRoomId(roomId + 1);
}
return ( return (
<div className="open"> <div className="open">
<div className="roomName-input"> <div className="roomName-input">
...@@ -99,7 +95,6 @@ function InputRoomNameArea() { ...@@ -99,7 +95,6 @@ function InputRoomNameArea() {
onKeyUpCapture={(e: React.KeyboardEvent<HTMLInputElement>) => { onKeyUpCapture={(e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') { if (e.key === 'Enter') {
addNewRoom(); addNewRoom();
handleRoomIdChange();
} }
else if (e.key === 'Escape') { else if (e.key === 'Escape') {
closeOpenDiv(); closeOpenDiv();
...@@ -109,7 +104,6 @@ function InputRoomNameArea() { ...@@ -109,7 +104,6 @@ function InputRoomNameArea() {
<div className="button-container"> <div className="button-container">
<button className="create-button" onClick={() =>{ <button className="create-button" onClick={() =>{
addNewRoom(); addNewRoom();
handleRoomIdChange();
}}>Submit</button> }}>Submit</button>
<button className="cancel-button" onClick={closeOpenDiv}>Cancel</button> <button className="cancel-button" onClick={closeOpenDiv}>Cancel</button>
</div> </div>
...@@ -292,9 +286,55 @@ function addNewComment(roomId: number, sender: string, content: string) { ...@@ -292,9 +286,55 @@ function addNewComment(roomId: number, sender: string, content: string) {
} }
export default function ChatRoom() { export default function ChatRoom() {
const [rooms, setRooms] = useState<RoomEntryProps[]>([]);
const [currentRoom, setCurrentRoom] = useState<MessageProps | null>(null);
useEffect(() => {
const fetchRooms = async () => {
try {
const response = await fetch("http://localhost:8080/room/list");
const result = await response.json();
if (result.code === 0) {
setRooms(result.data);
}
} catch (error) {
console.error("Error fetching rooms:", error);
}
}
fetchRooms();
}, []);
useEffect(() => {
if(currentRoom?.roomId) {
const fetchMessages = async () => {
try {
const response = await fetch(`http://localhost:8080/room/message/list?room_id=${currentRoom.roomId}`);
const result = await response.json();
if (result.code === 0) {
setCurrentRoom(prevRoom => ({
...prevRoom!,
messages: result.data
}));
}
} catch (error) {
console.error("Error fetching messages:", error);
}
fetchMessages();
}
}
}, [currentRoom?.roomId]);
const handleRoomClick = (roomId: number, roomName: string) => {
setCurrentRoom({
roomId: roomId,
roomName: roomName,
messages: []
});
}
return ( return (
<div className="chat-room"> <div className="chat-room">
<RoomEntry /> <RoomEntry rooms={rooms} onRoomClick={handleRoomClick}/>
<MessageItem <MessageItem
roomId={RoomRightNow.roomId} roomId={RoomRightNow.roomId}
roomName={RoomRightNow.roomName} roomName={RoomRightNow.roomName}
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment