-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
170 lines (145 loc) · 4.35 KB
/
index.js
File metadata and controls
170 lines (145 loc) · 4.35 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
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import compression from "compression";
import roadmapRoutes from "./src/routes/roadmapRoutes.js";
import playlistRoutes from "./src/routes/playlistRoutes.js";
import userRoutes from "./src/routes/userRoutes.js";
import neonDbService from "./src/services/neonDbService.js";
import {
helmetConfig,
generalLimiter,
sanitizeRequest,
} from "./src/middleware/security.js";
import {
productionLogger,
developmentLogger,
errorLogger,
requestTimer,
appLogger,
} from "./src/utils/logger.js";
import { validateEnvironmentVariables } from "./src/utils/helpers.js";
dotenv.config();
try {
validateEnvironmentVariables(["GEMINI_API_KEY", "YOUTUBE_API_KEY", "DATABASE_URL"]);
} catch (error) {
console.error("Environment validation failed:", error.message);
process.exit(1);
}
const app = express();
const PORT = 8001;
const NODE_ENV = process.env.NODE_ENV || "development";
app.set("trust proxy", 1);
app.use(helmetConfig);
app.use(compression());
const corsOptions = {
origin: process.env.ALLOWED_ORIGINS
? process.env.ALLOWED_ORIGINS.split(",").map((origin) => origin.trim())
: ["http://10.12.216.28:8081", "http://127.0.0.1:8081", "http://10.12.216.28:19000", "http://127.0.0.1:19000"],
credentials: true,
optionsSuccessStatus: 200,
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization", "x-api-key"],
};
app.use(cors(corsOptions));
app.use(express.json({ limit: "10mb" }));
app.use(express.urlencoded({ extended: true, limit: "10mb" }));
app.use(requestTimer);
app.use(sanitizeRequest);
if (NODE_ENV === "production") {
app.use(productionLogger);
} else {
app.use(developmentLogger);
}
app.use(generalLimiter);
app.use("/api/roadmaps", roadmapRoutes);
app.use("/api/playlists", playlistRoutes);
app.use("/api/users", userRoutes);
app.get("/health", (req, res) => {
res.json({
status: "OK",
message: "Server is running",
timestamp: new Date().toISOString(),
environment: NODE_ENV,
version: process.env.npm_package_version || "1.0.0",
});
});
app.get("/api/status", (req, res) => {
res.json({
success: true,
data: {
status: "operational",
services: {
gemini: !!process.env.GEMINI_API_KEY,
youtube: !!process.env.YOUTUBE_API_KEY,
database: !!process.env.DATABASE_URL,
},
timestamp: new Date().toISOString(),
},
});
});
app.use(errorLogger);
app.use((err, req, res, next) => {
appLogger.error("Unhandled error", err, {
method: req.method,
url: req.url,
userAgent: req.get("user-agent"),
ip: req.ip,
});
res.status(err.status || 500).json({
success: false,
error: {
code: err.code || "INTERNAL_SERVER_ERROR",
message:
NODE_ENV === "production" ? "Something went wrong!" : err.message,
details:
NODE_ENV === "production" ? "Please try again later" : err.message,
},
});
});
app.use("*", (req, res) => {
appLogger.warn("Route not found", {
method: req.method,
url: req.originalUrl,
ip: req.ip,
userAgent: req.get("user-agent"),
});
res.status(404).json({
success: false,
error: {
code: "NOT_FOUND",
message: "Route not found",
details: `The route ${req.originalUrl} does not exist`,
},
});
});
process.on("SIGTERM", async () => {
appLogger.info("SIGTERM received, shutting down gracefully");
process.exit(0);
});
process.on("SIGINT", async () => {
appLogger.info("SIGINT received, shutting down gracefully");
process.exit(0);
});
// Handle uncaught exceptions
process.on("uncaughtException", async (error) => {
appLogger.error("Uncaught Exception:", error);
process.exit(1);
});
// Handle unhandled promise rejections
// process.on("unhandledRejection", async (reason, promise) => {
// appLogger.error("Unhandled Rejection at:", promise, "reason:", reason);
// process.exit(1);
// });
app.listen(PORT, "0.0.0.0", () => {
console.log(`🚀 Server started successfully on http://0.0.0.0:${PORT}`);
console.log(`📊 Environment: ${NODE_ENV}`);
console.log(`📝 Logging to files: ${process.cwd()}/logs/`);
appLogger.info(`Server started successfully`, {
port: PORT,
environment: NODE_ENV,
timestamp: new Date().toISOString(),
});
appLogger.info("Testing logging system", { test: true });
});
export default app;