@@ -10,13 +10,53 @@ const PORT = process.env.PORT || 3000;
10
10
app . use ( express . json ( ) ) ;
11
11
12
12
// Health Check
13
+ // Health Check with Environment Variable Check and DB Connectivity Check
13
14
app . get ( "/health" , ( req , res ) => {
14
- res . json ( { status : "healthy" } ) ;
15
+ const missingEnvVars = [ ] ;
16
+
17
+ // Check for missing environment variables
18
+ const requiredEnvVars = [
19
+ { name : "DB_HOST" , example : "localhost" } ,
20
+ { name : "DB_USER" , example : "root" } ,
21
+ { name : "DB_PASSWORD" , example : "yourpassword" } ,
22
+ { name : "DB_NAME" , example : "yourdatabase" }
23
+ ] ;
24
+
25
+ requiredEnvVars . forEach ( ( envVar ) => {
26
+ if ( ! process . env [ envVar . name ] ) {
27
+ missingEnvVars . push ( { name : envVar . name , example : envVar . example } ) ;
28
+ }
29
+ } ) ;
30
+
31
+ // If any environment variables are missing, return an error
32
+ if ( missingEnvVars . length > 0 ) {
33
+ return res . status ( 500 ) . json ( {
34
+ status : "error" ,
35
+ message : "Missing environment variables" ,
36
+ missing : missingEnvVars
37
+ } ) ;
38
+ }
39
+
40
+ // Check MySQL connection using the already created connection from db.js
41
+ const connection = require ( "./db" ) ;
42
+
43
+ connection . ping ( ( err ) => {
44
+ if ( err ) {
45
+ return res . status ( 500 ) . json ( {
46
+ status : "error" ,
47
+ message : "Database connection failed" ,
48
+ error : err . message
49
+ } ) ;
50
+ }
51
+
52
+ // If the DB connection is successful, send a healthy status
53
+ res . json ( { status : "healthy" } ) ;
54
+ } ) ;
15
55
} ) ;
16
56
17
57
// Word Routes
18
58
app . use ( "/api/words" , wordsRouter ) ;
19
59
20
60
app . listen ( PORT , ( ) => {
21
- console . log ( `Server running on http://localhost:${ PORT } ` ) ;
22
- } ) ;
61
+ console . log ( `Server running on http://localhost:${ PORT } ` ) ;
62
+ } ) ;
0 commit comments