|
1 | 1 | // index.js |
2 | 2 | const express = require('express'); |
| 3 | +const mysql = require('mysql2/promise'); |
3 | 4 | const app = express(); |
4 | 5 |
|
| 6 | +// Create MySQL pool |
| 7 | +const pool = mysql.createPool({ |
| 8 | + host: process.env.DB_HOST || 'localhost', |
| 9 | + user: process.env.DB_USER || 'root', |
| 10 | + password: process.env.DB_PASSWORD || 'password', |
| 11 | + database: process.env.DB_NAME || 'testdb', |
| 12 | + waitForConnections: true, |
| 13 | + connectionLimit: 10 |
| 14 | +}); |
| 15 | + |
5 | 16 | // Root endpoint |
6 | | -app.get('/', (req, res) => { |
7 | | - res.json({ response: "deploy service with docker compose" }); |
| 17 | +app.get('/', async (req, res) => { |
| 18 | + try { |
| 19 | + const [rows] = await pool.query('SELECT NOW() as time'); |
| 20 | + res.json({ |
| 21 | + message: "deploy service with docker compose", |
| 22 | + db_time: rows[0].time |
| 23 | + }); |
| 24 | + } catch (error) { |
| 25 | + res.status(500).json({ error: "Database not connected" }); |
| 26 | + } |
8 | 27 | }); |
9 | 28 |
|
10 | | -// /will endpoint |
11 | 29 | app.get('/will', (req, res) => { |
12 | 30 | res.json({ response: "Welcome" }); |
13 | 31 | }); |
14 | 32 |
|
15 | | -// /ready endpoint |
16 | | -app.get('/ready', (req, res) => { |
17 | | - res.json({ response: "Great!, It works!" }); |
| 33 | +app.get('/ready', async (req, res) => { |
| 34 | + try { |
| 35 | + await pool.query('SELECT 1'); |
| 36 | + res.json({ status: "Database Ready" }); |
| 37 | + } catch (err) { |
| 38 | + res.status(500).json({ status: "Database Not Ready" }); |
| 39 | + } |
18 | 40 | }); |
19 | 41 |
|
20 | | -// Use PORT from environment or default 8080 |
21 | 42 | const PORT = process.env.PORT || 8080; |
22 | 43 |
|
23 | | -// Bind to 0.0.0.0 to expose outside container |
24 | 44 | app.listen(PORT, '0.0.0.0', () => { |
25 | 45 | console.log(`Server running on port ${PORT}`); |
26 | 46 | }); |
|
0 commit comments