feat: implement authentication layout and pages, including login and registration forms, with validation and API integration

This commit is contained in:
2025-09-06 19:19:20 +02:00
parent e7cf76a0d8
commit c7cb3f537d
11 changed files with 572 additions and 157 deletions

View File

@@ -0,0 +1,12 @@
// app/(auth)/layout.tsx
export default function AuthLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="flex items-center justify-center min-h-screen bg-gray-100">
{children}
</div>
);
}

View File

@@ -0,0 +1,112 @@
"use client";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import {
Form,
FormField,
FormItem,
FormLabel,
FormControl,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { LoginSchema, loginUser } from "@/lib/api";
import { useAuth } from "@/hooks/use-auth";
import { useState } from "react";
export default function LoginPage() {
const router = useRouter();
const { setToken } = useAuth();
const [error, setError] = useState<string | null>(null);
const form = useForm<z.infer<typeof LoginSchema>>({
resolver: zodResolver(LoginSchema),
defaultValues: { username: "", password: "" },
});
async function onSubmit(values: z.infer<typeof LoginSchema>) {
try {
setError(null);
const { token } = await loginUser(values);
setToken(token);
router.push("/"); // Redirect to homepage on successful login
} catch (err) {
setError("Invalid username or password.");
}
}
return (
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle>Login</CardTitle>
<CardDescription>
Enter your credentials to access your account.
</CardDescription>
</CardHeader>
<CardContent>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
{/* ... Form fields for username and password ... */}
<FormField
control={form.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>Username</FormLabel>
<FormControl>
<Input placeholder="frutiger" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input type="password" placeholder="••••••••" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{error && (
<p className="text-sm font-medium text-destructive">{error}</p>
)}
<Button
type="submit"
className="w-full"
disabled={form.formState.isSubmitting}
>
{form.formState.isSubmitting ? "Logging in..." : "Login"}
</Button>
</form>
</Form>
<p className="mt-4 text-center text-sm text-gray-600">
Don&apos;t have an account?{" "}
<Link
href="/register"
className="font-medium text-blue-600 hover:underline"
>
Register
</Link>
</p>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,125 @@
"use client";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import {
Form,
FormField,
FormItem,
FormLabel,
FormControl,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { RegisterSchema, registerUser } from "@/lib/api";
import { useState } from "react";
export default function RegisterPage() {
const router = useRouter();
const [error, setError] = useState<string | null>(null);
const form = useForm<z.infer<typeof RegisterSchema>>({
resolver: zodResolver(RegisterSchema),
defaultValues: { username: "", email: "", password: "" },
});
async function onSubmit(values: z.infer<typeof RegisterSchema>) {
try {
setError(null);
await registerUser(values);
// You can automatically log the user in here or just redirect them
router.push("/login");
} catch (err) {
setError("Username or email may already be taken.");
}
}
return (
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle>Create an Account</CardTitle>
<CardDescription>Enter your details to register.</CardDescription>
</CardHeader>
<CardContent>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
{/* ... Form fields for username, email, and password ... */}
<FormField
control={form.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>Username</FormLabel>
<FormControl>
<Input placeholder="frutiger" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input
type="email"
placeholder="aero@example.com"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input type="password" placeholder="••••••••" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{error && (
<p className="text-sm font-medium text-destructive">{error}</p>
)}
<Button
type="submit"
className="w-full"
disabled={form.formState.isSubmitting}
>
{form.formState.isSubmitting ? "Creating account..." : "Register"}
</Button>
</form>
</Form>
<p className="mt-4 text-center text-sm text-gray-600">
Already have an account?{" "}
<Link
href="/login"
className="font-medium text-blue-600 hover:underline"
>
Login
</Link>
</p>
</CardContent>
</Card>
);
}

View File

@@ -1,6 +1,8 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google"; import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css"; import "./globals.css";
import { AuthProvider } from "@/hooks/use-auth";
import { Toaster } from "@/components/ui/sonner";
const geistSans = Geist({ const geistSans = Geist({
variable: "--font-geist-sans", variable: "--font-geist-sans",
@@ -27,7 +29,10 @@ export default function RootLayout({
<body <body
className={`${geistSans.variable} ${geistMono.variable} antialiased`} className={`${geistSans.variable} ${geistMono.variable} antialiased`}
> >
{children} <AuthProvider>
{children}
<Toaster />
</AuthProvider>
</body> </body>
</html> </html>
); );

View File

@@ -1,155 +1,83 @@
"use client"; // app/page.tsx
import { cookies } from "next/headers";
import { useState, useEffect, FormEvent } from "react"; import { getFeed, getUserProfile } from "@/lib/api";
import { ThoughtCard } from "@/components/thought-card";
import { PostThoughtForm } from "@/components/post-thought-form";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea"; import Link from "next/link";
import { Card, CardHeader, CardContent } from "@/components/ui/card";
import { Alert } from "@/components/ui/alert";
interface Thought { // This is now an async Server Component
id: number; export default async function Home() {
author_id: number; const token = (await cookies()).get("auth_token")?.value ?? null;
content: string;
created_at: string; if (token) {
return <FeedPage token={token} />;
} else {
return <LandingPage />;
}
} }
export default function Home() { async function FeedPage({ token }: { token: string }) {
const [thoughts, setThoughts] = useState<Thought[]>([]); const feedData = await getFeed(token);
const [newThoughtContent, setNewThoughtContent] = useState(""); const authors = [...new Set(feedData.thoughts.map((t) => t.authorUsername))];
const [isLoading, setIsLoading] = useState(true); const userProfiles = await Promise.all(
const [error, setError] = useState<string | null>(null); authors.map((username) => getUserProfile(username, token).catch(() => null))
);
const fetchFeed = async () => { const authorDetails = new Map(
try { userProfiles
setError(null); .filter(Boolean)
const response = await fetch("http://localhost:8000/feed"); .map((user) => [user!.username, { avatarUrl: user!.avatarUrl }])
if (!response.ok) { );
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setThoughts(data.thoughts || []);
} catch (e: unknown) {
console.error("Failed to fetch feed:", e);
setError(
"Could not load the feed. The backend might be busy. Please try refreshing."
);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchFeed();
}, []);
const handleSubmitThought = async (e: FormEvent) => {
e.preventDefault();
if (!newThoughtContent.trim()) return;
try {
const response = await fetch("http://localhost:8000/thoughts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ content: newThoughtContent, author_id: 1 }),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
setNewThoughtContent("");
fetchFeed();
} catch (e: unknown) {
console.error("Failed to post thought:", e);
setError("Failed to post your thought. Please try again.");
}
};
return ( return (
<div className="font-sans bg-gradient-to-br from-sky-200 via-teal-100 to-green-200 min-h-screen text-gray-800"> <div className="container mx-auto max-w-2xl p-4 sm:p-6">
<div className="container mx-auto max-w-2xl p-4 sm:p-6"> <header className="my-6">
{/* Header */} <h1 className="text-3xl font-bold">Your Feed</h1>
<header className="text-center my-6"> </header>
<h1 <main className="space-y-6">
className="text-5xl font-bold text-white" <PostThoughtForm />
style={{ textShadow: "2px 2px 4px rgba(0,0,0,0.2)" }} {feedData.thoughts.map((thought) => (
> <ThoughtCard
Thoughts key={thought.id}
</h1> thought={thought}
<p className="text-white/80 mt-2"> author={{
Your space on the decentralized web. username: thought.authorUsername,
avatarUrl: authorDetails.get(thought.authorUsername)?.avatarUrl,
}}
/>
))}
{feedData.thoughts.length === 0 && (
<p className="text-center text-muted-foreground pt-8">
Your feed is empty. Follow some users to see their thoughts here!
</p> </p>
</header> )}
</main>
</div>
);
}
{/* New Thought Form */} function LandingPage() {
<Card className="bg-white/70 backdrop-blur-lg rounded-xl shadow-lg p-5 mb-8"> return (
<form onSubmit={handleSubmitThought}> <div className="font-sans min-h-screen text-gray-800 flex items-center justify-center">
<Textarea <div className="container mx-auto max-w-2xl p-4 sm:p-6 text-center">
value={newThoughtContent} <h1
onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => className="text-5xl font-bold"
setNewThoughtContent(e.target.value) style={{ textShadow: "2px 2px 4px rgba(0,0,0,0.1)" }}
} >
className="resize-none" Welcome to Thoughts
placeholder="What's on your mind?" </h1>
maxLength={128} <p className="text-muted-foreground mt-2">
/> Your space on the decentralized web.
<div className="flex justify-between items-center mt-3"> </p>
<span className="text-sm text-gray-500"> <div className="mt-8 flex justify-center gap-4">
{128 - newThoughtContent.length} characters remaining <Button asChild>
</span> <Link href="/login">Login</Link>
<Button </Button>
type="submit" <Button variant="secondary" asChild>
variant="default" <Link href="/register">Register</Link>
disabled={!newThoughtContent.trim()} </Button>
> </div>
Post
</Button>
</div>
</form>
</Card>
{/* Feed Section */}
<main>
{isLoading ? (
<p className="text-center text-gray-600">Loading feed...</p>
) : error ? (
<Alert variant="destructive" className="text-center">
{error}
</Alert>
) : thoughts.length === 0 ? (
<p className="text-center text-gray-600">
The feed is empty. Follow some users to see their thoughts!
</p>
) : (
<div className="space-y-4">
{thoughts.map((thought) => (
<Card
key={thought.id}
className="bg-white/80 backdrop-blur-lg rounded-xl shadow-lg p-4 transition-transform hover:scale-[1.02]"
>
<CardHeader className="flex items-center mb-2">
<div className="w-10 h-10 rounded-full bg-gradient-to-br from-green-300 to-sky-400 flex items-center justify-center font-bold text-white mr-3">
{thought.author_id}
</div>
<div>
<p className="font-bold">User {thought.author_id}</p>
<p className="text-xs text-gray-500">
{new Date(thought.created_at).toLocaleString()}
</p>
</div>
</CardHeader>
<CardContent>
<p className="text-gray-800 break-words">
{thought.content}
</p>
</CardContent>
</Card>
))}
</div>
)}
</main>
</div> </div>
</div> </div>
); );

View File

@@ -4,6 +4,7 @@ import { ThoughtCard } from "@/components/thought-card";
import { Calendar } from "lucide-react"; import { Calendar } from "lucide-react";
import { Card } from "@/components/ui/card"; import { Card } from "@/components/ui/card";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { cookies } from "next/headers";
interface ProfilePageProps { interface ProfilePageProps {
params: { username: string }; params: { username: string };
@@ -11,12 +12,13 @@ interface ProfilePageProps {
export default async function ProfilePage({ params }: ProfilePageProps) { export default async function ProfilePage({ params }: ProfilePageProps) {
const { username } = params; const { username } = params;
const token = (await cookies()).get("auth_token")?.value ?? null;
// Fetch data directly on the server. // Fetch data directly on the server.
// The `loading.tsx` file will be shown to the user during this fetch. // The `loading.tsx` file will be shown to the user during this fetch.
const [userResult, thoughtsResult] = await Promise.allSettled([ const [userResult, thoughtsResult] = await Promise.allSettled([
getUserProfile(username), getUserProfile(username, token),
getUserThoughts(username), getUserThoughts(username, token),
]); ]);
// Handle errors from the server-side fetch // Handle errors from the server-side fetch

View File

@@ -31,12 +31,14 @@
"@radix-ui/react-toggle": "^1.1.10", "@radix-ui/react-toggle": "^1.1.10",
"@radix-ui/react-toggle-group": "^1.1.11", "@radix-ui/react-toggle-group": "^1.1.11",
"@radix-ui/react-tooltip": "^1.2.8", "@radix-ui/react-tooltip": "^1.2.8",
"@types/js-cookie": "^3.0.6",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cmdk": "^1.1.1", "cmdk": "^1.1.1",
"date-fns": "^4.1.0", "date-fns": "^4.1.0",
"embla-carousel-react": "^8.6.0", "embla-carousel-react": "^8.6.0",
"input-otp": "^1.4.2", "input-otp": "^1.4.2",
"js-cookie": "^3.0.5",
"lucide-react": "^0.542.0", "lucide-react": "^0.542.0",
"next": "15.5.2", "next": "15.5.2",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
@@ -368,6 +370,8 @@
"@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="], "@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],
"@types/js-cookie": ["@types/js-cookie@3.0.6", "", {}, "sha512-wkw9yd1kEXOPnvEeEV1Go1MmxtBJL0RR79aOTAApecWFVu7w0NNXNqhcWgvw2YgZDYadliXkl14pa3WXw5jlCQ=="],
"@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="], "@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
"@types/json5": ["@types/json5@0.0.29", "", {}, "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ=="], "@types/json5": ["@types/json5@0.0.29", "", {}, "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ=="],
@@ -776,6 +780,8 @@
"jiti": ["jiti@2.5.1", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-twQoecYPiVA5K/h6SxtORw/Bs3ar+mLUtoPSc7iMXzQzK8d7eJ/R09wmTwAjiamETn1cXYPGfNnu7DMoHgu12w=="], "jiti": ["jiti@2.5.1", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-twQoecYPiVA5K/h6SxtORw/Bs3ar+mLUtoPSc7iMXzQzK8d7eJ/R09wmTwAjiamETn1cXYPGfNnu7DMoHgu12w=="],
"js-cookie": ["js-cookie@3.0.5", "", {}, "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw=="],
"js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], "js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
"js-yaml": ["js-yaml@4.1.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA=="], "js-yaml": ["js-yaml@4.1.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA=="],

View File

@@ -0,0 +1,118 @@
"use client";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
Form,
FormField,
FormItem,
FormControl,
FormMessage,
} from "@/components/ui/form";
import { Textarea } from "@/components/ui/textarea";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { CreateThoughtSchema, createThought } from "@/lib/api";
import { useAuth } from "@/hooks/use-auth";
import { toast } from "sonner";
import { Globe, Lock, Users } from "lucide-react";
export function PostThoughtForm() {
const router = useRouter();
const { token } = useAuth();
const form = useForm<z.infer<typeof CreateThoughtSchema>>({
resolver: zodResolver(CreateThoughtSchema),
defaultValues: { content: "", visibility: "Public" },
});
async function onSubmit(values: z.infer<typeof CreateThoughtSchema>) {
if (!token) {
toast.error("You must be logged in to post.");
return;
}
try {
await createThought(values, token);
toast.success("Your thought has been posted!");
form.reset();
router.refresh(); // This is the key to updating the feed
} catch (err) {
toast.error("Failed to post thought. Please try again.");
}
}
return (
<Card>
<CardContent className="p-4">
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="content"
render={({ field }) => (
<FormItem>
<FormControl>
<Textarea
placeholder="What's on your mind?"
className="resize-none"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex justify-between items-center">
<FormField
control={form.control}
name="visibility"
render={({ field }) => (
<Select
onValueChange={field.onChange}
defaultValue={field.value}
>
<FormControl>
<SelectTrigger className="w-[150px]">
<SelectValue placeholder="Visibility" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="Public">
<div className="flex items-center gap-2">
<Globe className="h-4 w-4" /> Public
</div>
</SelectItem>
<SelectItem value="FriendsOnly">
<div className="flex items-center gap-2">
<Users className="h-4 w-4" /> Friends Only
</div>
</SelectItem>
<SelectItem value="Private">
<div className="flex items-center gap-2">
<Lock className="h-4 w-4" /> Private
</div>
</SelectItem>
</SelectContent>
</Select>
)}
/>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? "Posting..." : "Post Thought"}
</Button>
</div>
</form>
</Form>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,40 @@
"use client";
import { createContext, useContext, useState, ReactNode } from "react";
import Cookies from "js-cookie";
interface AuthContextType {
token: string | null;
setToken: (token: string | null) => void;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export function AuthProvider({ children }: { children: ReactNode }) {
const [token, setTokenState] = useState<string | null>(() => {
return Cookies.get("auth_token") || null;
});
const setToken = (newToken: string | null) => {
setTokenState(newToken);
if (newToken) {
Cookies.set("auth_token", newToken, { expires: 7, secure: true });
} else {
Cookies.remove("auth_token");
}
};
return (
<AuthContext.Provider value={{ token, setToken }}>
{children}
</AuthContext.Provider>
);
}
export const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
};

View File

@@ -18,42 +18,107 @@ export const ThoughtSchema = z.object({
content: z.string(), content: z.string(),
visibility: z.enum(["Public", "FriendsOnly", "Private"]), visibility: z.enum(["Public", "FriendsOnly", "Private"]),
replyToId: z.uuid().nullable(), replyToId: z.uuid().nullable(),
createdAt: z.string().datetime(), createdAt: z.coerce.date(),
});
export const RegisterSchema = z.object({
username: z.string().min(3),
email: z.email(),
password: z.string().min(6),
});
export const LoginSchema = z.object({
username: z.string().min(3),
password: z.string().min(6),
});
export const CreateThoughtSchema = z.object({
content: z.string().min(1).max(128),
visibility: z.enum(["Public", "FriendsOnly", "Private"]).optional(),
replyToId: z.string().uuid().optional(),
}); });
export type User = z.infer<typeof UserSchema>; export type User = z.infer<typeof UserSchema>;
export type Thought = z.infer<typeof ThoughtSchema>; export type Thought = z.infer<typeof ThoughtSchema>;
export type Register = z.infer<typeof RegisterSchema>;
export type Login = z.infer<typeof LoginSchema>;
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000"; const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000";
async function apiFetch<T>( async function apiFetch<T>(
endpoint: string, endpoint: string,
options: RequestInit = {}, options: RequestInit = {},
schema: z.ZodType<T> schema: z.ZodType<T>,
token?: string | null
): Promise<T> { ): Promise<T> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
...(options.headers as Record<string, string>),
};
if (token) {
headers["Authorization"] = `Bearer ${token}`;
}
const response = await fetch(`${API_BASE_URL}${endpoint}`, { const response = await fetch(`${API_BASE_URL}${endpoint}`, {
...options, ...options,
headers: { headers,
"Content-Type": "application/json",
...options.headers,
},
}); });
if (!response.ok) { if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`); throw new Error(`API request failed with status ${response.status}`);
} }
if (response.status === 204) {
return null as T;
}
const data = await response.json(); const data = await response.json();
return schema.parse(data); return schema.parse(data);
} }
// --- User API Functions --- export const registerUser = (data: z.infer<typeof RegisterSchema>) =>
export const getUserProfile = (username: string) => apiFetch("/auth/register", {
apiFetch(`/users/${username}`, {}, UserSchema); method: "POST",
body: JSON.stringify(data),
}, UserSchema);
export const getUserThoughts = (username: string) => export const loginUser = (data: z.infer<typeof LoginSchema>) =>
apiFetch("/auth/login", {
method: "POST",
body: JSON.stringify(data),
}, z.object({ token: z.string() }));
export const getFeed = (token: string) =>
apiFetch(
"/feed",
{},
z.object({ thoughts: z.array(ThoughtSchema) }),
token
);
// --- User API Functions ---
export const getUserProfile = (username: string, token: string | null) =>
apiFetch(`/users/${username}`, {}, UserSchema, token);
export const getUserThoughts = (username: string, token: string | null) =>
apiFetch( apiFetch(
`/users/${username}/thoughts`, `/users/${username}/thoughts`,
{}, {},
z.object({ thoughts: z.array(ThoughtSchema) }) z.object({ thoughts: z.array(ThoughtSchema) }),
token
);
export const createThought = (
data: z.infer<typeof CreateThoughtSchema>,
token: string
) =>
apiFetch(
"/thoughts",
{
method: "POST",
body: JSON.stringify(data),
},
ThoughtSchema,
token
); );

View File

@@ -36,12 +36,14 @@
"@radix-ui/react-toggle": "^1.1.10", "@radix-ui/react-toggle": "^1.1.10",
"@radix-ui/react-toggle-group": "^1.1.11", "@radix-ui/react-toggle-group": "^1.1.11",
"@radix-ui/react-tooltip": "^1.2.8", "@radix-ui/react-tooltip": "^1.2.8",
"@types/js-cookie": "^3.0.6",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cmdk": "^1.1.1", "cmdk": "^1.1.1",
"date-fns": "^4.1.0", "date-fns": "^4.1.0",
"embla-carousel-react": "^8.6.0", "embla-carousel-react": "^8.6.0",
"input-otp": "^1.4.2", "input-otp": "^1.4.2",
"js-cookie": "^3.0.5",
"lucide-react": "^0.542.0", "lucide-react": "^0.542.0",
"next": "15.5.2", "next": "15.5.2",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",