aboutsummaryrefslogtreecommitdiff
path: root/src/get.ts
blob: adba0fccb45b464c66d9dcbdd3d82fa7b64a5a94 (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import type { Sql } from "postgres";

const book = Bun.file("book/the_wonderful_wizard_of_oz.txt");
const book_text = await book.text()
const pars = book_text.split(/\n\s*\n/);

export async function get_home(context: { headers: Record<string, string | null> }) {
  const file = Bun.file("page/index.txt");

  let res = new Response(
    await file.text() +
    `the following is a randomly selected excerpt from THE WONDERFUL WIZARD 
OF OZ by L. FRANK BAUM\n\n` +
    pars[Math.floor(Math.random() * pars.length)]
  );

  if (context.headers["user-agent"] ?? "".includes("curl")) {
    res.headers.set("X-Message", "Okay I Like It, Picasso");
  }

  return res;
}

export async function get_id(
  context: { params: Record<"id", string>, headers: Record<string, string | null> },
  sql: Sql) {

  let id = context.params.id;

  let get_query = false;
  if (id.endsWith("+")) {
    id = id.slice(0, id.length - 1);
    get_query = true;
  }

  let db_res = await sql`
  SELECT * FROM urls
  WHERE id=${id}
  `

  if (!db_res.length) {
    return new Response(`url for id '${id}' not found.`, { status: 404 });
  } else if (get_query) {
    return new Response(`trkt.in/${id} -> ${db_res[0]['url']}`);
  } else {
    await sql`
    INSERT INTO tracking (id,clicks)
    VALUES(${id},1)
    ON CONFLICT ON CONSTRAINT tracking_id_key 
    DO UPDATE
      SET clicks=tracking.clicks+1
    `;
  }

  const url = new URL(db_res[0]['url']);

  const html = `
  <!DOCTYPE html>
  <html>
  <head><title>trkt</title></head>
  <body>
    <p>redirecting to <a href="${url.href}">${url.href}</a></p>
  </body>
  </html>
  `;

  const res = new Response(html, { status: 301 });
  res.headers.set("Location", url.href);
  res.headers.set("Cache-Control", "max-age=120");
  res.headers.set("Content-Type", "text/html");

  if (context.headers["user-agent"] ?? "".includes("curl")) {
    res.headers.set("X-Message", "Okay I Like It, Picasso");
  }

  return res;
}

export async function get_create() {
  const file = Bun.file("page/create.html");
  let res = new Response(await file.text());

  res.headers.set("Content-Type", "text/html");

  return res;
}