Commit 868dc59c authored by 健杭 徐's avatar 健杭 徐
Browse files

AddMessage/Room api

parent 2fe2722d
...@@ -17,11 +17,12 @@ const ( ...@@ -17,11 +17,12 @@ const (
) )
type Message struct { type Message struct {
MessageId int `json:"message_id"` MessageId int `json:"message_id"`
RoomId int `json:"room_id"` RoomId int `json:"room_id"`
Sender string `json:"sender"` Profile_id int `json:"profile_id"`
Content string `json:"content"` Sender string `json:"sender"`
Timestamp string `json:"timestamp"` Content string `json:"content"`
Timestamp string `json:"timestamp"`
} }
type RoomPreviewInfo struct { type RoomPreviewInfo struct {
...@@ -37,6 +38,10 @@ type Response struct { ...@@ -37,6 +38,10 @@ type Response struct {
Data interface{} `json:"data"` Data interface{} `json:"data"`
} }
type RoomAddRes struct {
RoomId int `json:"room_id"`
}
var db *sql.DB var db *sql.DB
func main() { func main() {
...@@ -72,7 +77,28 @@ func main() { ...@@ -72,7 +77,28 @@ func main() {
} }
func AddNewRoom(c *gin.Context) { func AddNewRoom(c *gin.Context) {
var room RoomPreviewInfo
if err := c.ShouldBindJSON(&room); err != nil {
c.JSON(400, Response{Code: 400, Msg: "Invalid input", Data: nil})
return
}
var roomId int
err := db.QueryRow(
"INSERT INTO rooms (room_name) VALUES ($1) RETURNING room_id",
room.RoomName,
).Scan(&roomId)
if err != nil {
c.JSON(500, Response{Code: 500, Msg: "Failed to add room", Data: nil})
return
}
room.RoomId = roomId
room.LastMessage = ""
room.LastMessageTime = ""
c.JSON(200, RoomAddRes{
RoomId: room.RoomId,
})
log.Printf("New room added: %+v", room)
} }
func GetRoomList(c *gin.Context) { func GetRoomList(c *gin.Context) {
...@@ -93,8 +119,8 @@ func AddMessage(c *gin.Context) { ...@@ -93,8 +119,8 @@ func AddMessage(c *gin.Context) {
var messageId int var messageId int
err := db.QueryRow( err := db.QueryRow(
"INSERT INTO messages (roomId, 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.Sender, message.Content, message.RoomId, message.Profile_id, message.Sender, message.Content,
).Scan(&messageId) ).Scan(&messageId)
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})
...@@ -107,6 +133,7 @@ func AddMessage(c *gin.Context) { ...@@ -107,6 +133,7 @@ func AddMessage(c *gin.Context) {
Msg: "Message added successfully", Msg: "Message added successfully",
Data: message, Data: message,
}) })
log.Printf("New message added: %+v", message)
} }
func GetMessageList(c *gin.Context) { func GetMessageList(c *gin.Context) {
......
'use client'; 'use client';
import { METHODS } from "http";
import "./ChatRoom.css"; import "./ChatRoom.css";
import React, { useState } from "react"; import React, { useState } from "react";
...@@ -48,7 +49,10 @@ function RoomEntry (props: RoomEntryProps) { ...@@ -48,7 +49,10 @@ function RoomEntry (props: RoomEntryProps) {
function InputRoomNameArea() { function InputRoomNameArea() {
const [roomId, setRoomId] = useState(0); const [roomId, setRoomId] = useState(0);
function handleRoomIdChange() {
setRoomId(roomId + 1);
}
return ( return (
<div className="open"> <div className="open">
<div className="roomName-input"> <div className="roomName-input">
...@@ -60,6 +64,7 @@ function InputRoomNameArea() { ...@@ -60,6 +64,7 @@ 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();
...@@ -67,7 +72,10 @@ function InputRoomNameArea() { ...@@ -67,7 +72,10 @@ function InputRoomNameArea() {
}} }}
/> />
<div className="button-container"> <div className="button-container">
<button className="create-button" onClick={addNewRoom}>Submit</button> <button className="create-button" onClick={() =>{
addNewRoom();
handleRoomIdChange();
}}>Submit</button>
<button className="cancel-button" onClick={closeOpenDiv}>Cancel</button> <button className="cancel-button" onClick={closeOpenDiv}>Cancel</button>
</div> </div>
</div> </div>
...@@ -75,26 +83,39 @@ function InputRoomNameArea() { ...@@ -75,26 +83,39 @@ function InputRoomNameArea() {
); );
} }
function addNewRoom() { async function addNewRoom() {
const RoomNameInput = (document.getElementsByClassName("RoomNameInput")[0] as HTMLInputElement).value; const RoomNameInput = (document.getElementsByClassName("RoomNameInput")[0] as HTMLInputElement).value;
if (RoomNameInput === "") { if (RoomNameInput === "") {
alert("Please enter a room name."); alert("Please enter a room name.");
return; return;
} }
const chatList = document.getElementsByClassName("chat-list")[0]; try {
const newRoom = document.createElement("div"); const response = await fetch ("http://localhost:8080/room/add", {
method: 'POST',
newRoom.className = "chat-item"; headers: { 'Content-Type': 'application/json' },
newRoom.innerHTML = ` body: JSON.stringify({ room_name: RoomNameInput })
<img src="${RoomProfile}" alt="Avatar" class="avatar" /> })
<div class="chat-info" >
<h3>${RoomNameInput}</h3> const result = await response.json();
<span class="chat-message">New message</span>
<span class="chat-time">Time</span> const chatList = document.getElementsByClassName("chat-list")[0];
</div> const newRoom = document.createElement("div");
`;
chatList.appendChild(newRoom); newRoom.className = "chat-item";
newRoom.innerHTML = `
<img src="${RoomProfile}" alt="Avatar" class="avatar" />
<div class="chat-info" >
<h3>${RoomNameInput}</h3>
<span class="chat-message">New message</span>
<span class="chat-time">Time</span>
</div>
`;
chatList.appendChild(newRoom);
} catch (error) {
console.error("Error adding new room:", error);
alert("Failed to create room. Please try again.");
}
closeOpenDiv(); closeOpenDiv();
} }
...@@ -198,22 +219,43 @@ function addNewComment(roomId: number, sender: string, content: string) { ...@@ -198,22 +219,43 @@ function addNewComment(roomId: number, sender: string, content: string) {
profileId = Math.floor(Math.random() * (Profile.length-1)); profileId = Math.floor(Math.random() * (Profile.length-1));
} }
const message = document.createElement("div"); try {
message.className = "message"; const response = fetch('http://localhost:8080/room/message/add', {
message.innerHTML = ` method: 'POST',
<img src="${Profile[profileId]}" alt="${sender}'s avatar" class="avatar"> headers: { 'Content-Type': 'application/json' },
<div class="message-content"> body: JSON.stringify({ roomId, profile_id: profileId, sender, content })
<div class="message-info"> });
<span class="message-sender">${sender}</span> response.then(res => res.json()).then(data => {
<span class="message-time">${new Date().toLocaleTimeString()}</span> if (data.code !== 0) {
alert(`Error: ${data.msg}`);
return;
}
const message = document.createElement("div");
message.className = "message";
message.innerHTML = `
<img src="${Profile[profileId]}" alt="${sender}'s avatar" class="avatar">
<div class="message-content">
<div class="message-info">
<span class="message-sender">${sender}</span>
<span class="message-time">${new Date().toLocaleTimeString()}</span>
</div>
<p class="message-text">${content}</p>
</div> </div>
<p class="message-text">${content}</p> `;
</div>
`;
(document.getElementsByClassName("Inputarea")[0] as HTMLInputElement).value = ''; (document.getElementsByClassName("Inputarea")[0] as HTMLInputElement).value = '';
messageList[0].appendChild(message); messageList[0].appendChild(message);
}).catch(error => {
console.error("Error adding new comment:", error);
alert("Failed to send message. Please try again.");
});
}
catch (error) {
console.error("Error in addNewComment:", error);
alert("An error occurred while sending the message.");
}
} }
export default function ChatRoom() { export default function ChatRoom() {
......
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