aboutsummaryrefslogtreecommitdiff
path: root/src/post.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/post.ts')
-rw-r--r--src/post.ts55
1 files changed, 55 insertions, 0 deletions
diff --git a/src/post.ts b/src/post.ts
new file mode 100644
index 0000000..538ff00
--- /dev/null
+++ b/src/post.ts
@@ -0,0 +1,55 @@
+import type { Sql } from "postgres";
+
+import { reserved_ids } from "./reserved"
+
+export async function post_c(body: any, sql: Sql) {
+ let custom_id = true;
+
+ let form = {
+ url: body['url'],
+ id: body['id'].trim()
+ }
+
+ try {
+ form.url = new URL(form.url);
+ } catch (_) {
+ return new Response(`'${form.url}' is not a valid URL.`, { status: 400 });
+ }
+
+ if (!form.id.trim()) {
+ custom_id = false;
+ const hasher = new Bun.CryptoHasher("md5");
+ hasher.update(form.url.href);
+ form.id = hasher.digest("hex").slice(0, 11);
+ }
+
+ const valid_re = /^[A-z0-9_-]+$/;
+ if (!form.id.match(valid_re) || form.id.match(valid_re).length != 1) {
+ return new Response(`'${form.id}' must be of A-Z|a-z|0-9|_|-`, { status: 400 });
+ }
+
+ let db_id_exists = await sql`
+ SELECT * FROM urls
+ WHERE id=${form.id}
+ `;
+
+ if (db_id_exists.length > 0 && custom_id) {
+ return new Response(
+ `custom id already exists.\ntrkt.in/${form.id} -> ${db_id_exists[0]["url"]}`,
+ { status: 409 }
+ );
+ }
+
+ if (reserved_ids.includes(form.id)) {
+ return new Response(`'${form.id}' is a reserved link.`, { status: 403 });
+ }
+
+ if (db_id_exists.length == 0) {
+ await sql`
+ INSERT INTO urls(id, url)
+ VALUES(${form.id}, ${form.url.href})
+ `;
+ }
+
+ return new Response(`trkt.in/${form.id} -> ${form.url.href}`);
+}