-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
56 lines (54 loc) · 1.48 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
48
49
50
51
52
53
54
55
56
import "std/dotenv/load.ts";
/// <reference types="./types.d.ts" />
import {
Application,
Context,
isHttpError,
Status,
STATUS_TEXT,
} from "oak/mod.ts";
import { green, yellow } from "std/fmt/colors.ts";
import memeRouter from "./routes/meme.ts";
import userRouter from "./routes/user.ts";
import utilsRouter from "./routes/utils.ts";
import { Accepts } from "accepts/mod.ts";
const app = new Application();
const port = 18080;
app.use(async (ctx: Context, next) => {
ctx.response.headers.append('Access-Control-Allow-Origin', '*')
ctx.accepts = new Accepts(ctx.request.headers);
await next();
});
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
if (isHttpError(err)) {
switch (err.status) {
case Status.NotFound:
ctx.response.body = { message: STATUS_TEXT[404] };
ctx.response.status=404;
break;
case Status.InternalServerError:
ctx.response.body = { message: STATUS_TEXT[500] };
ctx.response.status=500;
break;
default:
}
} else {
throw err;
}
}
});
app.use(memeRouter.routes());
app.use(userRouter.routes());
app.use(utilsRouter.routes());
app.use((ctx) => {
ctx.throw(404);
});
app.addEventListener("listen", ({ secure, hostname, port }) => {
const protocol = secure ? "https://" : "http://";
const url = `${protocol}${hostname ?? "localhost"}:${port}`;
console.log(`${yellow("Listening on:")} ${green(url)}`);
});
await app.listen({ port });