From 96982b85e23af2a24841c3c44e598ae71f78abf6 Mon Sep 17 00:00:00 2001 From: Shav Kinderlehrer Date: Sun, 15 Oct 2023 00:14:32 -0400 Subject: Implement get --- src/get.ts | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/get.ts (limited to 'src/get.ts') diff --git a/src/get.ts b/src/get.ts new file mode 100644 index 0000000..a9eebbc --- /dev/null +++ b/src/get.ts @@ -0,0 +1,61 @@ +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 }) { + 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 }, + sql: Sql) { + + const id = context.params.id; + 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 }); + } + + const url = new URL(db_res[0]['url']); + + const html = ` + + + trkt + +

redirecting to ${url.href}

+ + + `; + + const res = new Response(html, { status: 301 }); + res.headers.set("Location", url.href); + res.headers.set("Cache-Control", "max-age=3"); + res.headers.set("Content-Type", "text/html"); + + if (context.headers["user-agent"] ?? "".includes("curl")) { + res.headers.set("X-Message", "Okay I Like It, Picasso"); + } + + console.log(res); + return res; +} -- cgit v1.2.3