summaryrefslogtreecommitdiff
path: root/app/routes/api.posts.tsx
blob: 8ef7639373c4ca72533986e3bbc157a3d2dc7731 (plain)
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
import type { Route } from "./+types/api.posts";
import { createPost, listPosts } from "~/lib/db.server";
import { renderMarkdown } from "~/lib/md.server";

export async function loader() {
  const posts = listPosts();
  return Response.json(
    posts.map((p) => ({ ...p, html: renderMarkdown(p.content) }))
  );
}

export async function action({ request }: Route.ActionArgs) {
  if (request.method !== "POST") {
    return Response.json({ error: "Method not allowed" }, { status: 405 });
  }

  const token = process.env.REGISTER_TOKEN;
  const auth = request.headers.get("Authorization") ?? "";
  if (!token || auth !== `Bearer ${token}`) {
    return Response.json({ error: "Unauthorized" }, { status: 401 });
  }

  let content: string;
  const ct = request.headers.get("content-type") ?? "";
  if (ct.includes("application/json")) {
    const body = (await request.json()) as { content?: unknown };
    content = String(body.content ?? "").trim();
  } else {
    const form = await request.formData();
    content = String(form.get("content") ?? "").trim();
  }

  if (!content) {
    return Response.json({ error: "content is required" }, { status: 400 });
  }
  if (content.length > 10000) {
    return Response.json(
      { error: "content too long (max 10000 chars)" },
      { status: 400 }
    );
  }

  const post = createPost({ id: crypto.randomUUID(), content });
  return Response.json(
    { ...post, html: renderMarkdown(post.content) },
    { status: 201 }
  );
}