Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
// app/api/posts/[id]/route.ts import { NextRequest, NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { getUser } from '@/lib/auth'; // GET /api/posts/:id export async function GET( request: NextRequest, { params }: { params: { id: string } }, ) { const post = await prisma.post.findUnique({ where: { id: params.id }, }); if (!post) { return NextResponse.json({ error: 'Not found' }, { status: 404 }); } return NextResponse.json(post); } // PATCH /api/posts/:id export async function PATCH( request: NextRequest, { params }: { params: { id: string } }, ) { const user = await getUser(); if (!user) { return NextResponse.json({ error: 'Unauthorised' }, { status: 401 }); } const body = await request.json(); const { title, content } = body; const updated = await prisma.post.update({ where: { id: params.id, authorId: user.id }, data: { title, content, updatedAt: new Date() }, }); return NextResponse.json(updated); } // DELETE /api/posts/:id export async function DELETE( _request: NextRequest, { params }: { params: { id: string } }, ) { const user = await getUser(); if (!user) { return NextResponse.json({ error: 'Unauthorised' }, { status: 401 }); } await prisma.post.delete({ where: { id: params.id, authorId: user.id } }); return new Response(null, { status: 204 }); }
Result
Open