Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
77 lines (60 loc) · 1.99 KB
/
Copy pathserver.ts
File metadata and controls
77 lines (60 loc) · 1.99 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import http from "node:http";
import cors from "cors";
import express from "express";
import morgan from "morgan";
import path from "node:path";
import { config } from "../util/config.js";
import { initDatabase } from "../util/database.js";
import { initRabbitMQ } from "../util/events.js";
import { createLogger, createLogStream } from "../util/log.js";
import { errorHandler } from "./middleware/error.js";
import routes, { isFederationRequest } from "./routes.js";
import { engine } from "express-handlebars";
const Log = createLogger("API");
export class APIServer {
server: http.Server;
app: express.Application;
public constructor(server?: http.Server) {
this.app = express();
this.app.use(cors());
this.app.set("trust proxy", config().security.trust_proxy);
morgan.token("mode", (req) => (isFederationRequest(req.headers) ? "fed" : "api"));
morgan.token("type", (req) => req.headers["content-type"]);
morgan.token("accept", (req) => req.headers.accept);
if (config().http.log)
this.app.use(
morgan(config().http.log_format, {
stream: createLogStream("HTTP"),
skip(_req, res) {
const log = config().http.log;
const skip = log?.includes(res.statusCode.toString()) ?? false;
return log?.charAt(0) === "-" ? skip : !skip;
},
}),
);
this.app.engine("handlebars", engine());
this.app.set("view engine", "handlebars");
this.app.set(
"views",
path.join(import.meta.filename, "..", "..", "..", "..", "assets", "views"),
);
this.app.use(
"/public",
express.static(
path.join(import.meta.filename, "..", "..", "..", "..", "assets", "public"),
),
);
this.app.use("/", routes);
this.app.use(errorHandler);
this.server = server ?? http.createServer();
this.server.on("request", this.app);
}
public async listen(port: number) {
this.server.on("listening", () => {
Log.msg(`Listening on port ${port}`);
});
await initDatabase();
await initRabbitMQ(false);
if (!this.server.listening) this.server.listen(port);
}
}