-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
80 lines (63 loc) · 1.89 KB
/
server.js
File metadata and controls
80 lines (63 loc) · 1.89 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
78
79
80
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const dotenv = require("dotenv");
const helmet = require("helmet");
const ExchangeRateService = require("./services/ExchangeRateService");
const logger = require("./utils/logger");
dotenv.config();
const app = express();
app.use(helmet());
app.use(cors(require("./config/corsOptions")));
app.use(morgan("combined"));
// env 파일 접근 제한
app.use((req, res, next) => {
if (req.path.includes(".env")) {
return res.status(403).send("Access Forbidden");
}
next();
});
const exchangeService = new ExchangeRateService();
exchangeService.on("error", (error) => {
console.error("Error fetching rate:", error);
});
app.get("/exchange-rate", (req, res) => {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
});
const sendRate = (rate) => {
res.write(`data: ${JSON.stringify(rate)}\n\n`);
};
// 현재 환율 정보가 있으면 바로 보내줌
const currentRate = exchangeService.getLastRate();
if (currentRate) sendRate(currentRate);
exchangeService.on("newRate", sendRate);
req.on("close", () => {
exchangeService.removeListener("newRate", sendRate);
});
});
exchangeService.start();
app.get("/", (req, res) => {
res.send("Welcome to the Exchange Rate API server.");
});
app.get("/status", (req, res) => {
res.json({
status: "ok",
clientsCount: exchangeRateService.getClientsCount(),
uptime: process.uptime(),
memoryUsage: process.memoryUsage(),
});
});
app.use((req, res) => {
res.status(404).send("Sorry, that route doesn't exist.");
});
app.use((err, req, res, next) => {
logger.error("Server Error:", err);
res.status(500).send("Something broke!");
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
logger.info(`Server started on port ${PORT}`);
});