summaryrefslogtreecommitdiff
path: root/src/routes/api/blog.json/+server.ts
blob: f416647800d6a4ca2785d97d078b83a54980ae0e (plain) (blame)
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
/*** IMPORT ------------------------------------------- ***/

import { error, json } from "@sveltejs/kit";

/*** EXPORT ------------------------------------------- ***/

export const POST = async({ fetch, request }) => {
  try {
    const { filename } = await request.json();

    const response = await fetch(`https://blog.webb.page/${String(filename)}`, {
      headers: { "Content-Type": "text/plain" },
      method: "GET"
    });

    const memo = parseMemo(await response.text());
    memo.push(`   <span class="special-char">[</span><a href="https://blog.webb.page/${String(filename).split(".txt")[0]}">READ</a><span class="special-char">]</span>`, "\n");

    return json({ content: memo.join("\n") });
  } catch(welp) {
    console.error(`Error fetching memo: ${String(welp)}`);
    return error(500);
  }
};

/*** HELPER ------------------------------------------- ***/

function parseMemo(text: string): string {
  const intro = text.split(/^Body$/m)[0];
  const lines = intro.split("\n").filter(Boolean);
  const format = [""];
  let firstLine = "";

  lines.map((line, index) => {
    if (index === 1)
      firstLine = "   " + line.split(/\s+\B/)[1].trim();

    if (index === 2) {
      firstLine += ` • ${line.trim()}`;
      format.push(firstLine);
    }

    if (index === 4)
      format.push("   " + line.trim());
  });

  return format;
}