aboutsummaryrefslogtreecommitdiff
path: root/src/get.ts
diff options
context:
space:
mode:
authorShav Kinderlehrer <[email protected]>2023-10-15 00:14:32 -0400
committerShav Kinderlehrer <[email protected]>2023-10-15 00:14:32 -0400
commit96982b85e23af2a24841c3c44e598ae71f78abf6 (patch)
treeccdedb6e6b4e5d84c259a90d7cb9e9eb1202f2b6 /src/get.ts
parente05f78146ef386a81b39d3e05afa145c1e23f679 (diff)
downloadurl-shortener-96982b85e23af2a24841c3c44e598ae71f78abf6.tar.gz
url-shortener-96982b85e23af2a24841c3c44e598ae71f78abf6.zip
Implement get
Diffstat (limited to 'src/get.ts')
-rw-r--r--src/get.ts61
1 files changed, 61 insertions, 0 deletions
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<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) {
+
+ 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 = `
+ <!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=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;
+}