fix: add lesson 6
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getPollById } from "@/lib/data";
|
||||
import type { Poll } from "@/types";
|
||||
|
||||
interface RouteParams {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
// STAP 3: GET /api/polls/[id] — enkele poll ophalen
|
||||
// (Dit bestand is COMPLEET van Les 5. Dit is stap 3 van Les 5.)
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: RouteParams
|
||||
): Promise<NextResponse> {
|
||||
const { id } = await params;
|
||||
const poll = getPollById(id);
|
||||
|
||||
if (!poll) {
|
||||
return NextResponse.json(
|
||||
{ error: "Poll niet gevonden" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json<Poll>(poll);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { votePoll } from "@/lib/data";
|
||||
|
||||
interface RouteParams {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
interface VoteBody {
|
||||
optionIndex: number;
|
||||
}
|
||||
|
||||
// STAP 4: POST /api/polls/[id]/vote — stem uitbrengen
|
||||
//
|
||||
// Wat moet je doen?
|
||||
// 1. Haal het id op uit params (await!)
|
||||
// 2. Lees de request body en cast naar VoteBody
|
||||
// 3. Valideer: is optionIndex een number?
|
||||
// 4. Roep votePoll(id, body.optionIndex) aan
|
||||
// 5. Als het resultaat undefined is: return 404
|
||||
// 6. Anders: return de geüpdatete poll als JSON
|
||||
|
||||
export async function POST(
|
||||
request: Request,
|
||||
{ params }: RouteParams
|
||||
): Promise<NextResponse> {
|
||||
// Implementeer je POST handler hier
|
||||
return NextResponse.json({ error: "Nog niet geimplementeerd" }, { status: 501 });
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getPolls, createPoll } from "@/lib/data";
|
||||
import type { Poll, CreatePollBody } from "@/types";
|
||||
|
||||
// GET /api/polls — alle polls ophalen
|
||||
export async function GET(): Promise<NextResponse<Poll[]>> {
|
||||
const polls = getPolls();
|
||||
return NextResponse.json(polls);
|
||||
}
|
||||
|
||||
// POST /api/polls — nieuwe poll aanmaken
|
||||
export async function POST(request: Request): Promise<NextResponse> {
|
||||
const body: CreatePollBody = await request.json();
|
||||
|
||||
if (!body.question || !body.options || body.options.length < 2) {
|
||||
return NextResponse.json(
|
||||
{ error: "Vraag en minstens 2 opties zijn verplicht" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const newPoll = createPoll(body.question, body.options);
|
||||
return NextResponse.json(newPoll, { status: 201 });
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
// BONUS: Maak een formulier om een nieuwe poll aan te maken
|
||||
//
|
||||
// Benodigde state:
|
||||
// - question: string
|
||||
// - options: string[] (start met ["", ""])
|
||||
// - isSubmitting: boolean
|
||||
// - error: string | null
|
||||
//
|
||||
// Wat moet je bouwen?
|
||||
// 1. Een input voor de vraag
|
||||
// 2. Inputs voor de opties (minimaal 2, maximaal 6)
|
||||
// 3. Knoppen om opties toe te voegen/verwijderen
|
||||
// 4. Een submit knop die POST naar /api/polls
|
||||
// 5. Na success: redirect naar / met router.push("/")
|
||||
|
||||
export default function CreatePollPage() {
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<h1 className="text-2xl font-bold text-gray-900 mb-6">
|
||||
Nieuwe Poll Aanmaken
|
||||
</h1>
|
||||
<p className="text-gray-400 italic">
|
||||
Bonus: bouw hier het create formulier
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
"use client";
|
||||
|
||||
// STAP 7: Error boundary
|
||||
//
|
||||
// Dit bestand vangt fouten op in de route.
|
||||
// MOET een client component zijn ("use client" staat al bovenaan).
|
||||
//
|
||||
// Props die je krijgt:
|
||||
// - error: Error — het error object met .message
|
||||
// - reset: () => void — functie om de pagina opnieuw te proberen
|
||||
//
|
||||
// Bouw een nette error pagina met:
|
||||
// - Een titel "Er ging iets mis!"
|
||||
// - De error message
|
||||
// - Een "Probeer opnieuw" knop die reset() aanroept
|
||||
|
||||
export default function Error({
|
||||
error,
|
||||
reset,
|
||||
}: {
|
||||
error: Error;
|
||||
reset: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="text-center py-16">
|
||||
<p>Er ging iets mis: {error.message}</p>
|
||||
<button onClick={() => reset()}>Probeer opnieuw</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
@@ -0,0 +1 @@
|
||||
@import "tailwindcss";
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import "./globals.css";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "QuickPoll — Stem op alles",
|
||||
description: "Maak en deel polls met je vrienden",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<html lang="nl">
|
||||
<body className="min-h-screen bg-gray-50 text-gray-900">
|
||||
{/*
|
||||
STAP 1: Bouw hier een navigatiebalk met:
|
||||
- Logo/titel "QuickPoll" (links) die linkt naar /
|
||||
- Een link naar / ("Polls")
|
||||
- Een link naar /create ("Nieuwe Poll")
|
||||
|
||||
Tip: gebruik <Link> van "next/link", niet <a>
|
||||
Tip: gebruik Tailwind classes voor styling
|
||||
*/}
|
||||
|
||||
<main className="max-w-4xl mx-auto px-4 py-8">{children}</main>
|
||||
|
||||
<footer className="text-center text-gray-400 text-sm py-8">
|
||||
© 2025 QuickPoll — NOVI Hogeschool Les 5
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// STAP 7: Loading state
|
||||
//
|
||||
// Dit bestand wordt automatisch getoond terwijl een pagina laadt.
|
||||
// Bouw een skeleton loader met Tailwind's animate-pulse class.
|
||||
//
|
||||
// Voorbeeld:
|
||||
// <div className="animate-pulse">
|
||||
// <div className="h-8 bg-gray-200 rounded w-1/3 mb-4" />
|
||||
// </div>
|
||||
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div>
|
||||
<p>Laden...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import Link from "next/link";
|
||||
|
||||
// STAP 7: Not found pagina
|
||||
//
|
||||
// Wordt getoond als een pagina niet bestaat.
|
||||
// Bouw een nette 404 pagina met een link terug naar home.
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<div className="text-center py-16">
|
||||
<h2 className="text-4xl font-bold text-gray-900 mb-4">404</h2>
|
||||
<p className="text-gray-600 mb-6">Deze pagina bestaat niet.</p>
|
||||
<Link href="/" className="text-purple-600 hover:underline">
|
||||
Terug naar home
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import Link from "next/link";
|
||||
import { getPolls } from "@/lib/data";
|
||||
import type { Poll } from "@/types";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default function HomePage() {
|
||||
// STAP 2: Haal alle polls op met getPolls()
|
||||
// Dit is een Server Component — je kunt gewoon functies aanroepen!
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900 mb-2">Actieve Polls</h1>
|
||||
<p className="text-gray-500 mb-8">Klik op een poll om te stemmen</p>
|
||||
|
||||
<div className="grid gap-4">
|
||||
{/*
|
||||
STAP 2: Map over de polls en toon voor elke poll:
|
||||
- De vraag (poll.question)
|
||||
- Het aantal opties en stemmen
|
||||
- De opties als tags/badges
|
||||
- Wrap het in een <Link> naar /poll/{poll.id}
|
||||
|
||||
Tip: maak een helper functie voor het totaal aantal stemmen:
|
||||
const totalVotes = (poll: Poll): number =>
|
||||
poll.votes.reduce((sum, v) => sum + v, 0);
|
||||
*/}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
// STAP 7: Error boundary voor poll detail pagina
|
||||
//
|
||||
// Dit bestand vangt fouten op in deze route.
|
||||
|
||||
export default function ErrorPoll({
|
||||
error,
|
||||
reset,
|
||||
}: {
|
||||
error: Error & { digest?: string };
|
||||
reset: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto text-center py-12">
|
||||
<h2 className="text-2xl font-bold text-red-600 mb-4">
|
||||
Oeps! Iets ging fout
|
||||
</h2>
|
||||
<p className="text-gray-600 mb-6">{error.message}</p>
|
||||
<button
|
||||
onClick={reset}
|
||||
className="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700"
|
||||
>
|
||||
Probeer opnieuw
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// STAP 7: Loading state voor poll detail pagina
|
||||
//
|
||||
// Dit bestand wordt automatisch getoond terwijl de poll detail pagina laadt.
|
||||
// Bouw een skeleton loader die lijkt op de echte content.
|
||||
|
||||
export default function LoadingPoll() {
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto animate-pulse">
|
||||
<div className="h-10 bg-gray-200 rounded w-3/4 mb-8" />
|
||||
<div className="space-y-4">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="bg-white rounded-lg border p-4 h-16"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import Link from "next/link";
|
||||
|
||||
export default function PollNotFound() {
|
||||
return (
|
||||
<div className="text-center py-16">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">
|
||||
Poll niet gevonden
|
||||
</h2>
|
||||
<p className="text-gray-600 mb-6">
|
||||
Deze poll bestaat niet of is verwijderd.
|
||||
</p>
|
||||
<Link href="/" className="text-purple-600 hover:underline">
|
||||
Bekijk alle polls
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { getPollById } from "@/lib/data";
|
||||
import { VoteForm } from "@/components/VoteForm";
|
||||
import type { Metadata } from "next";
|
||||
|
||||
interface PageProps {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
// STAP 5: generateMetadata — dynamische pagina titel
|
||||
//
|
||||
// Deze functie genereert de <title> tag voor SEO.
|
||||
// Haal de poll op en return de vraag als titel.
|
||||
|
||||
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
|
||||
const { id } = await params;
|
||||
const poll = getPollById(id);
|
||||
|
||||
return {
|
||||
title: poll ? `${poll.question} — QuickPoll` : "Poll niet gevonden",
|
||||
};
|
||||
}
|
||||
|
||||
// STAP 5: PollPage — de poll detail pagina
|
||||
//
|
||||
// Wat moet je doen?
|
||||
// 1. Haal het id op uit params (await!)
|
||||
// 2. Zoek de poll met getPollById(id)
|
||||
// 3. Als de poll niet bestaat: roep notFound() aan
|
||||
// 4. Render de poll vraag als <h1>
|
||||
// 5. Render de <VoteForm poll={poll} /> component
|
||||
|
||||
export default async function PollPage({ params }: PageProps) {
|
||||
// Implementeer je pagina hier
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<p>Implementeer deze pagina (zie stap 5 in de opdracht)</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import type { Poll } from "@/types";
|
||||
|
||||
interface VoteFormProps {
|
||||
poll: Poll;
|
||||
}
|
||||
|
||||
// STAP 6: VoteForm — de stem interface
|
||||
//
|
||||
// Dit is een CLIENT component ("use client" staat bovenaan).
|
||||
// Hier mag je wel useState en onClick gebruiken!
|
||||
//
|
||||
// Benodigde state:
|
||||
// - selectedOption: number | null (welke optie is geselecteerd)
|
||||
// - hasVoted: boolean (heeft de gebruiker al gestemd)
|
||||
// - isLoading: boolean (wordt het formulier verstuurd)
|
||||
// - currentPoll: Poll (de huidige poll data, update na stemmen)
|
||||
//
|
||||
// Wat moet je bouwen?
|
||||
// 1. Toon alle opties als klikbare knoppen (voor het stemmen)
|
||||
// 2. Highlight de geselecteerde optie met purple border
|
||||
// 3. Een "Stem!" knop die een POST doet naar /api/polls/{id}/vote
|
||||
// 4. Na het stemmen: toon de resultaten met progress bars en percentages
|
||||
// 5. Toon een "Terug" link naar de homepage
|
||||
|
||||
export function VoteForm({ poll }: VoteFormProps) {
|
||||
const [selectedOption, setSelectedOption] = useState<number | null>(null);
|
||||
const [hasVoted, setHasVoted] = useState<boolean>(false);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||
const [currentPoll, setCurrentPoll] = useState<Poll>(poll);
|
||||
|
||||
const totalVotes: number = currentPoll.votes.reduce((sum, v) => sum + v, 0);
|
||||
|
||||
function getPercentage(votes: number): number {
|
||||
if (totalVotes === 0) return 0;
|
||||
return Math.round((votes / totalVotes) * 100);
|
||||
}
|
||||
|
||||
async function handleVote(): Promise<void> {
|
||||
if (selectedOption === null || isLoading) return;
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/polls/${currentPoll.id}/vote`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ optionIndex: selectedOption }),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const updatedPoll: Poll = await response.json();
|
||||
setCurrentPoll(updatedPoll);
|
||||
setHasVoted(true);
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Nog niet gestemd — toon opties
|
||||
if (!hasVoted) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{currentPoll.options.map((option, idx) => (
|
||||
<button
|
||||
key={idx}
|
||||
onClick={() => setSelectedOption(idx)}
|
||||
disabled={isLoading}
|
||||
className={`w-full text-left p-4 rounded-lg border-2 transition ${
|
||||
selectedOption === idx
|
||||
? "border-purple-500 bg-purple-50"
|
||||
: "border-gray-200 hover:border-purple-300"
|
||||
}`}
|
||||
>
|
||||
<span className="font-medium">{option}</span>
|
||||
</button>
|
||||
))}
|
||||
|
||||
<button
|
||||
onClick={handleVote}
|
||||
disabled={selectedOption === null || isLoading}
|
||||
className="w-full bg-purple-600 text-white py-3 rounded-lg hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition font-medium"
|
||||
>
|
||||
{isLoading ? "Aan het stemmen..." : "Stem!"}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Wel gestemd — toon resultaten
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<p className="text-green-600 font-medium text-lg">
|
||||
✓ Bedankt voor je stem!
|
||||
</p>
|
||||
|
||||
<div className="space-y-4">
|
||||
{currentPoll.options.map((option, idx) => (
|
||||
<div key={idx}>
|
||||
<div className="flex justify-between mb-2">
|
||||
<span className="font-medium">{option}</span>
|
||||
<span className="text-sm text-gray-600">
|
||||
{currentPoll.votes[idx]} stemmen ({getPercentage(currentPoll.votes[idx])}%)
|
||||
</span>
|
||||
</div>
|
||||
<div className="w-full bg-gray-200 rounded-full h-3">
|
||||
<div
|
||||
className="bg-purple-600 h-3 rounded-full transition-all"
|
||||
style={{
|
||||
width: `${getPercentage(currentPoll.votes[idx])}%`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Link
|
||||
href="/"
|
||||
className="block text-center text-purple-600 hover:underline mt-6"
|
||||
>
|
||||
← Terug naar polls
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { Poll } from "@/types";
|
||||
|
||||
export const polls: Poll[] = [
|
||||
{
|
||||
id: "1",
|
||||
question: "Wat is de beste code editor?",
|
||||
options: ["VS Code", "Cursor", "Vim", "WebStorm"],
|
||||
votes: [12, 25, 5, 3],
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
question: "Wat is de beste programmeertaal?",
|
||||
options: ["TypeScript", "Python", "Rust", "Go"],
|
||||
votes: [18, 15, 8, 4],
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
question: "Welk framework heeft de toekomst?",
|
||||
options: ["Next.js", "Remix", "Astro", "SvelteKit"],
|
||||
votes: [22, 6, 10, 7],
|
||||
},
|
||||
];
|
||||
|
||||
let nextId = 4;
|
||||
|
||||
export function getPolls(): Poll[] {
|
||||
return polls;
|
||||
}
|
||||
|
||||
export function getPollById(id: string): Poll | undefined {
|
||||
return polls.find((poll) => poll.id === id);
|
||||
}
|
||||
|
||||
export function createPoll(question: string, options: string[]): Poll {
|
||||
const newPoll: Poll = {
|
||||
id: String(nextId++),
|
||||
question,
|
||||
options,
|
||||
votes: new Array(options.length).fill(0),
|
||||
};
|
||||
polls.push(newPoll);
|
||||
return newPoll;
|
||||
}
|
||||
|
||||
export function votePoll(
|
||||
pollId: string,
|
||||
optionIndex: number
|
||||
): Poll | undefined {
|
||||
const poll = polls.find((p) => p.id === pollId);
|
||||
if (!poll || optionIndex < 0 || optionIndex >= poll.options.length) {
|
||||
return undefined;
|
||||
}
|
||||
poll.votes[optionIndex]++;
|
||||
return poll;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
export function middleware(request: NextRequest): NextResponse {
|
||||
const start = Date.now();
|
||||
|
||||
console.log(`[${request.method}] ${request.nextUrl.pathname}`);
|
||||
|
||||
const response = NextResponse.next();
|
||||
response.headers.set("x-request-time", String(Date.now() - start));
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ["/api/:path*", "/poll/:path*"],
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
export interface Poll {
|
||||
id: string;
|
||||
question: string;
|
||||
options: string[];
|
||||
votes: number[];
|
||||
}
|
||||
|
||||
export interface CreatePollBody {
|
||||
question: string;
|
||||
options: string[];
|
||||
}
|
||||
Reference in New Issue
Block a user