Files
blog-manager/app/api/posts/route.ts
2026-11-01 13:23:44 -05:00

29 lines
1.1 KiB
TypeScript

import { HttpError } from "@/lib/errors";
import { readJson, route } from "@/lib/http";
import { categoryCounts, mutatePosts, readPosts, tagCounts } from "@/lib/store";
import { validatePost } from "@/lib/validate";
export const dynamic = "force-dynamic";
export const GET = route(async () => {
const { posts, revision } = await readPosts();
return Response.json({ posts, revision, categories: categoryCounts(posts), tags: tagCounts(posts) });
});
/** Body: { post: PostInput, revision? } */
export const POST = route(async (req) => {
const body = await readJson<{ post?: unknown; revision?: string }>(req);
const { post, errors } = validatePost(body.post);
if (!post) throw new HttpError(400, "invalid post", errors);
const { result, revision } = await mutatePosts(body.revision, (posts) => {
if (posts.some((p) => p.slug === post.slug)) {
throw new HttpError(409, `a post with slug "${post.slug}" already exists`);
}
const created = { id: Math.max(0, ...posts.map((p) => p.id)) + 1, ...post };
posts.push(created);
return created;
});
return Response.json({ post: result, revision }, { status: 201 });
});