@@ -10,13 +10,53 @@ const PORT = process.env.PORT || 3000;
1010app . use ( express . json ( ) ) ;
1111
1212// Health Check
13+ // Health Check with Environment Variable Check and DB Connectivity Check
1314app . 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+ } ) ;
1555} ) ;
1656
1757// Word Routes
1858app . use ( "/api/words" , wordsRouter ) ;
1959
2060app . 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