initial commit
This commit is contained in:
28
app/api/posts/route.ts
Normal file
28
app/api/posts/route.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
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 });
|
||||
});
|
||||
Reference in New Issue
Block a user