-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
84 lines (68 loc) · 1.92 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import cors from "cors";
import dotenv from "dotenv";
import express, { NextFunction, Request, Response } from "express";
import * as OpenApiValidator from "express-openapi-validator";
import helmet from "helmet";
import morgan from "morgan";
import "reflect-metadata";
import swaggerUi from "swagger-ui-express";
import { createConnection } from "typeorm";
import YAML from "yamljs";
import { articleController } from "./controller/article-controller";
import { dataController } from "./controller/data-controller";
import { userController } from "./controller/user-controller";
dotenv.config();
/**
* App Variables
*/
if (!process.env.PORT) {
process.exit(1);
}
export async function main(): Promise<void> {
const PORT: number = parseInt(process.env.PORT as string, 10);
const app = express();
await createConnection();
const apiSpec = process.env.API_PATH || "../../api-bundle.yaml";
/**
* App Configuration
*/
app.use(morgan("combined"));
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use(
OpenApiValidator.middleware({
apiSpec,
validateRequests: true,
// validateResponses: true,
ignoreUndocumented: true
})
);
const swaggerDocument = YAML.load(apiSpec);
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument));
/**
* Routes
*/
app.use("/user", userController());
app.use("/article", articleController());
app.use("/data", dataController());
/**
* Error Handler
*/
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
if (err.name === "UnauthorizedError") {
res.status(401).json({ error: "Invalid Authorization" });
return;
}
res
.status(err.statusCode || err.status || 500)
.json({ error: err.message || "Unexpected error" });
});
/**
* Server Activation
*/
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
}
main();