-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
71 lines (63 loc) · 1.92 KB
/
Copy pathroute.ts
File metadata and controls
71 lines (63 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { NextResponse } from "next/server";
import { isAuthorized } from "@/lib/auth";
import {
createPost,
listPublishedPosts,
PostConflictError,
} from "@/lib/posts";
import type { CreatePostInput } from "@/lib/types";
// Cosmos SDK requires the Node.js runtime (not Edge).
export const runtime = "nodejs";
// Always read fresh data.
export const dynamic = "force-dynamic";
/** GET /api/posts?pageSize=10&cursor=<token> — list published posts. */
export async function GET(request: Request) {
const url = new URL(request.url);
const pageSizeRaw = Number(url.searchParams.get("pageSize"));
const pageSize =
Number.isFinite(pageSizeRaw) && pageSizeRaw > 0 && pageSizeRaw <= 50
? pageSizeRaw
: 10;
const cursor = url.searchParams.get("cursor");
const page = await listPublishedPosts({
pageSize,
continuationToken: cursor,
});
return NextResponse.json(page);
}
/** POST /api/posts — create a post (requires AUTHOR_API_KEY). */
export async function POST(request: Request) {
if (!isAuthorized(request)) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
let body: Partial<CreatePostInput>;
try {
body = await request.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
const { title, excerpt, content, author } = body;
if (!title || !excerpt || !content || !author) {
return NextResponse.json(
{ error: "title, excerpt, content and author are required." },
{ status: 400 },
);
}
try {
const post = await createPost({
slug: body.slug ?? title,
title,
excerpt,
content,
author,
tags: body.tags ?? [],
status: body.status ?? "draft",
});
return NextResponse.json(post, { status: 201 });
} catch (err) {
if (err instanceof PostConflictError) {
return NextResponse.json({ error: err.message }, { status: 409 });
}
throw err;
}
}