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

AddMessage/Room api

parent 2fe2722d
......@@ -19,6 +19,7 @@ const (
type Message struct {
MessageId int `json:"message_id"`
RoomId int `json:"room_id"`
Profile_id int `json:"profile_id"`
Sender string `json:"sender"`
Content string `json:"content"`
Timestamp string `json:"timestamp"`
......@@ -37,6 +38,10 @@ type Response struct {
Data interface{} `json:"data"`
}
type RoomAddRes struct {
RoomId int `json:"room_id"`
}
var db *sql.DB
func main() {
......@@ -72,7 +77,28 @@ func main() {
}
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) {
......@@ -93,8 +119,8 @@ func AddMessage(c *gin.Context) {
var messageId int
err := db.QueryRow(
"INSERT INTO messages (roomId, sender, content, timestamp) VALUES ($1, $2, NOW()) RETURNING message_id",
message.RoomId, message.Sender, message.Content,
"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,
).Scan(&messageId)
if err != nil {
c.JSON(500, Response{Code: 500, Msg: "Failed to add message", Data: nil})
......@@ -107,6 +133,7 @@ func AddMessage(c *gin.Context) {
Msg: "Message added successfully",
Data: message,
})
log.Printf("New message added: %+v", message)
}
func GetMessageList(c *gin.Context) {
......
'use client';
import { METHODS } from "http";
import "./ChatRoom.css";
import React, { useState } from "react";
......@@ -48,6 +49,9 @@ function RoomEntry (props: RoomEntryProps) {
function InputRoomNameArea() {
const [roomId, setRoomId] = useState(0);
function handleRoomIdChange() {
setRoomId(roomId + 1);
}
return (
<div className="open">
......@@ -60,6 +64,7 @@ function InputRoomNameArea() {
onKeyUpCapture={(e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
addNewRoom();
handleRoomIdChange();
}
else if (e.key === 'Escape') {
closeOpenDiv();
......@@ -67,7 +72,10 @@ function InputRoomNameArea() {
}}
/>
<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>
</div>
</div>
......@@ -75,13 +83,22 @@ function InputRoomNameArea() {
);
}
function addNewRoom() {
async function addNewRoom() {
const RoomNameInput = (document.getElementsByClassName("RoomNameInput")[0] as HTMLInputElement).value;
if (RoomNameInput === "") {
alert("Please enter a room name.");
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 newRoom = document.createElement("div");
......@@ -95,6 +112,10 @@ function addNewRoom() {
</div>
`;
chatList.appendChild(newRoom);
} catch (error) {
console.error("Error adding new room:", error);
alert("Failed to create room. Please try again.");
}
closeOpenDiv();
}
......@@ -198,6 +219,18 @@ function addNewComment(roomId: number, sender: string, content: string) {
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");
message.className = "message";
message.innerHTML = `
......@@ -214,6 +247,15 @@ function addNewComment(roomId: number, sender: string, content: string) {
(document.getElementsByClassName("Inputarea")[0] as HTMLInputElement).value = '';
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() {
......
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