-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
57 lines (47 loc) · 1.28 KB
/
index.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
57
import { Status } from "./src/utils/declarations";
require("dotenv").config();
import * as Koa from "koa";
import * as cors from "@koa/cors";
import { userAgent } from "koa-useragent";
import database from "./src/database";
import { router } from "./router";
import bunyanLogger from "./src/utils/logger";
const port = process.env.PORT || 4000;
const app = new Koa();
const logger = bunyanLogger.child({ component: "index" });
app.use(async function responseTime(ctx, next) {
const t1 = Date.now();
await next();
const t2 = Date.now();
ctx.set("X-Response-Time", `${Math.ceil(t2 - t1)}ms`);
});
// For cors with options
app.use(
cors({
origin: "*",
})
);
// For useragent detection
app.use(userAgent);
// For managing body. We're only allowing json.
app.use(require("koa-bodyparser")());
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
err.status = err.statusCode || err.status || 500;
ctx.body = {
status: Status.ERROR,
message: err.message,
data: {},
};
ctx.app.emit("error", err, ctx);
}
});
app.use(require("koa-bodyparser")());
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(port, async () => {
await database.connect();
await logger.info(`Library Server listening on port ${port}`);
});