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

AddMessage/Room api

parent 2fe2722d
...@@ -19,6 +19,7 @@ const ( ...@@ -19,6 +19,7 @@ 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"`
Profile_id int `json:"profile_id"`
Sender string `json:"sender"` Sender string `json:"sender"`
Content string `json:"content"` Content string `json:"content"`
Timestamp string `json:"timestamp"` Timestamp string `json:"timestamp"`
...@@ -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,6 +49,9 @@ function RoomEntry (props: RoomEntryProps) { ...@@ -48,6 +49,9 @@ 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">
...@@ -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,13 +83,22 @@ function InputRoomNameArea() { ...@@ -75,13 +83,22 @@ 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;
} }
try {
const response = await fetch ("http://localhost:8080/room/add", {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ room_name: RoomNameInput })
})
const result = await response.json();
const chatList = document.getElementsByClassName("chat-list")[0]; const chatList = document.getElementsByClassName("chat-list")[0];
const newRoom = document.createElement("div"); const newRoom = document.createElement("div");
...@@ -95,6 +112,10 @@ function addNewRoom() { ...@@ -95,6 +112,10 @@ function addNewRoom() {
</div> </div>
`; `;
chatList.appendChild(newRoom); chatList.appendChild(newRoom);
} catch (error) {
console.error("Error adding new room:", error);
alert("Failed to create room. Please try again.");
}
closeOpenDiv(); closeOpenDiv();
} }
...@@ -198,6 +219,18 @@ function addNewComment(roomId: number, sender: string, content: string) { ...@@ -198,6 +219,18 @@ function addNewComment(roomId: number, sender: string, content: string) {
profileId = Math.floor(Math.random() * (Profile.length-1)); profileId = Math.floor(Math.random() * (Profile.length-1));
} }
try {
const response = fetch('http://localhost:8080/room/message/add', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ roomId, profile_id: profileId, sender, content })
});
response.then(res => res.json()).then(data => {
if (data.code !== 0) {
alert(`Error: ${data.msg}`);
return;
}
const message = document.createElement("div"); const message = document.createElement("div");
message.className = "message"; message.className = "message";
message.innerHTML = ` message.innerHTML = `
...@@ -214,6 +247,15 @@ function addNewComment(roomId: number, sender: string, content: string) { ...@@ -214,6 +247,15 @@ function addNewComment(roomId: number, sender: string, content: string) {
(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