feat(chat): add POST /api/messages endpoint and update ChatInput to send messages

This commit is contained in:
Chneemann 2026-08-30 19:44:48 +02:00
parent af10837072
commit ac8392569b
No known key found for this signature in database
3 changed files with 154 additions and 8 deletions

View file

@ -47,7 +47,11 @@ export default async function ChannelPage({
<ChatMessages channelName={channel.name} messages={channelMessages} />
{/* Input Field */}
<ChatInput />
<ChatInput
serverId={server.id}
channelId={channel.id}
channelName={channel.name}
/>
</div>
);
}

72
app/api/messages/route.ts Normal file
View file

@ -0,0 +1,72 @@
/**
* @file app/api/messages/route.ts
* @description API route handler for creating new messages in a channel.
*/
import { auth } from "@/auth";
import { db } from "@/db";
import { members, messages } from "@/db/schema";
import { and, eq } from "drizzle-orm";
import { NextResponse } from "next/server";
/**
* Handles POST requests to create a new message within a specific channel and server.
*
* @param {Request} req - The incoming HTTP request containing content, channelId, and serverId in the JSON body.
* @returns {Promise<NextResponse>} JSON response containing the created message object or an error message.
*/
export async function POST(req: Request) {
try {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { content, channelId, serverId } = await req.json();
if (!content?.trim() || !channelId || !serverId) {
return NextResponse.json(
{ error: "Missing parameters" },
{ status: 400 },
);
}
// Find member ID of the current user for this server
const [member] = await db
.select()
.from(members)
.where(
and(
eq(members.userId, session.user.id),
eq(members.serverId, serverId),
),
)
.limit(1);
if (!member) {
return NextResponse.json(
{ error: "Not a member of this server" },
{ status: 403 },
);
}
// Insert message into the database
const [newMessage] = await db
.insert(messages)
.values({
content: content.trim(),
channelId,
memberId: member.id,
})
.returning();
return NextResponse.json(newMessage, { status: 201 });
} catch (error) {
console.error("API Message POST error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 },
);
}
}

View file

@ -1,21 +1,91 @@
/**
* @file components/chat/ChatInput.tsx
* @description Client component providing an input field for composing and sending chat messages.
* @description Client component providing an input field to create messages via REST API.
*/
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
/**
* Renders the input container component for sending messages in a chat channel.
* Props for the ChatInput component.
*
* @returns {JSX.Element} The rendered chat input UI element.
* @interface ChatInputProps
* @property {string} channelName - The name of the channel displayed in the input placeholder.
* @property {string} channelId - The ID of the channel where the message will be sent.
* @property {string} serverId - The ID of the server containing the channel.
*/
export function ChatInput() {
interface ChatInputProps {
channelName: string;
channelId: string;
serverId: string;
}
/**
* Renders an input field for sending chat messages within a channel.
*
* @param {ChatInputProps} props - Component properties.
* @returns {JSX.Element} The ChatInput component.
*/
export function ChatInput({
channelName,
channelId,
serverId,
}: ChatInputProps) {
const [content, setContent] = useState("");
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
/**
* Handles key press events, submitting the message on 'Enter' (without Shift).
*
* @param {React.KeyboardEvent<HTMLInputElement>} e - The keyboard event.
*/
const handleKeyDown = async (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
if (!content.trim() || isLoading) return;
try {
setIsLoading(true);
const response = await fetch("/api/messages", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
content,
channelId,
serverId,
}),
});
if (!response.ok) {
throw new Error("Error while sending");
}
setContent("");
router.refresh();
} catch (error) {
console.error("Error sending the message:", error);
} finally {
setIsLoading(false);
}
}
};
return (
<div className=" bg-background shrink-0">
<div className="bg-background shrink-0">
<div className="bg-surface border border-surface rounded-lg p-2.5 flex items-center focus-within:ring-1 focus-within:ring-accent transition-all">
<input
type="text"
placeholder="Nachricht an #allgemein"
className="w-full bg-transparent outline-none text-foreground placeholder-muted text-sm"
value={content}
onChange={(e) => setContent(e.target.value)}
onKeyDown={handleKeyDown}
disabled={isLoading}
placeholder={`Message to #${channelName}`}
className="w-full bg-transparent outline-none text-foreground placeholder-muted text-sm disabled:opacity-50"
/>
</div>
</div>