blob: 538ff00fdd00048902ef3be7b979229fb7a54268 (
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
|
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}`);
}
|