-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
140 lines (120 loc) · 3.44 KB
/
server.js
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const http = require('http');
const socketIO = require('socket.io');
const path = require('path');
const { router: roomsRouter, initializeSocket } = require('./routes/api/rooms');
const routes = require('./routes');
const KafkaService = require('./services/kafkaService');
const kafkaService = new KafkaService();
const app = express();
const server = http.createServer(app);
const PORT = process.env.PORT || 5000;
const uploadRoutes = require("./routes/api/files");
// trust proxy 설정 추가
app.set("trust proxy", 1);
// CORS 설정
const corsOptions = {
origin: [
"https://bootcampchat-fe.run.goorm.site",
"http://localhost:3000",
"https://localhost:3000",
"http://0.0.0.0:3000",
"https://0.0.0.0:3000",
],
credentials: true,
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: [
"Content-Type",
"Authorization",
"x-auth-token",
"x-session-id",
"Cache-Control",
"Pragma",
],
exposedHeaders: ["x-auth-token", "x-session-id"],
};
// 기본 미들웨어
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// OPTIONS 요청에 대한 처리
app.options("*", cors(corsOptions));
// 정적 파일 제공
app.use("/uploads", express.static(path.join(__dirname, "uploads")));
// 요청 로깅
if (process.env.NODE_ENV === "development") {
app.use((req, res, next) => {
console.log(
`[${new Date().toISOString()}] ${req.method} ${req.originalUrl}`
);
next();
});
}
// 기본 상태 체크
app.get("/health", (req, res) => {
res.json({
status: "ok",
timestamp: new Date().toISOString(),
env: process.env.NODE_ENV,
});
});
// API 라우트 마운트
app.use("/api", routes);
// Socket.IO 설정
const io = socketIO(server, { cors: corsOptions, path: "/api/socket" });
require("./sockets/chat")(io);
app.set('io', io);
// Socket.IO 객체 전달
initializeSocket(io);
// 404 에러 핸들러
app.use((req, res) => {
console.log("404 Error:", req.originalUrl);
res.status(404).json({
success: false,
message: "요청하신 리소스를 찾을 수 없습니다.",
path: req.originalUrl,
});
});
// 글로벌 에러 핸들러
app.use((err, req, res, next) => {
console.error("Server error:", err);
res.status(err.status || 500).json({
success: false,
message: err.message || "서버 에러가 발생했습니다.",
...(process.env.NODE_ENV === "development" && { stack: err.stack }),
});
});
// 업로드 핸들러
app.use("/api/upload", uploadRoutes);
// 서버 시작
mongoose.connect(process.env.MONGO_URI)
.then(async () => {
console.log('MongoDB Connected');
await kafkaService.init();
console.log('Kafka Connected');
server.listen(PORT, '0.0.0.0', () => {
console.log(`Server running on port ${PORT}`);
console.log("Environment:", process.env.NODE_ENV);
console.log("API Base URL:", `http://0.0.0.0:${PORT}/api`);
});
})
.catch((err) => {
console.error("Server startup error:", err);
process.exit(1);
});
process.on('SIGTERM', async () => {
console.log('SIGTERM received');
await kafkaService.disconnect();
server.close(() => {
mongoose.connection.close(false, () => {
process.exit(0);
});
});
});
process.on('uncaughtException', err => {
console.log(err)
})
module.exports = { app, server };