-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
47 lines (39 loc) · 1.32 KB
/
main.ts
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
import { Application, Router } from "https://deno.land/x/[email protected]/mod.ts";
import { oakCors } from "https://deno.land/x/[email protected]/mod.ts";
import { getArchivedUrl } from "./lib/archive_url.ts";
import { config } from "./lib/config.ts";
const AUTH_HEADER = `Bearer ${config().SECRET_KEY}`;
const router = new Router();
router.get("/", async (context) => {
const targetUrl = context.request.url.searchParams.get("url");
if (!targetUrl) {
context.response.status = 400;
return;
}
const authHeader = context.request.headers.get("Authorization");
if (authHeader !== AUTH_HEADER) {
context.response.status = 401;
return;
}
try {
const archivedUrl = await getArchivedUrl(targetUrl);
if (!archivedUrl) {
throw new Error("did not get an archived url");
}
const shouldRedirect = context.request.url.searchParams.get("redirect");
if (shouldRedirect === "1") {
context.response.status = 302;
context.response.headers.set("Location", archivedUrl);
} else {
context.response.body = archivedUrl;
}
} catch (error) {
context.response.status = 500;
context.response.body = { error };
}
});
const app = new Application();
app.use(oakCors()); // Enable CORS for All Routes
app.use(router.routes());
app.use(router.allowedMethods());
await app.listen({ port: 8000 });