-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
56 lines (49 loc) Β· 1.49 KB
/
index.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
const express = require('express');
const mysql = require('mysql2');
const app = express();
const port = 3000;
// Create MySQL connection
var connection = mysql.createConnection({
host: 'mysql-service', // Updated to match the service name in docker-compose.yml
user: 'root',
password: 'password', // Updated to match the password in docker-compose.yml
database: 'mysql_db', // Updated to match the database name in docker-compose.yml
port: 3306
});
// Connect to MySQL
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL:', err.stack);
return;
}
console.log('Connected to MySQL as id ' + connection.threadId);
});
// Define route
app.get('/', (req, res) => {
connection.query('SELECT * FROM products', (error, results) => {
if (error) {
return res.status(500).send('Error querying the database');
}
if (results.length > 0) {
const productNames = results.map(product => product.name).join(', ');
res.send(`node-service:<br>Products: ${productNames}`);
} else {
res.send('No products found in the database.');
}
});
});
// Start the server
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
// Optionally, end the connection when the app is stopped
process.on('SIGINT', () => {
connection.end((err) => {
if (err) {
console.error('Error closing MySQL connection:', err.stack);
} else {
console.log('MySQL connection closed.');
}
process.exit();
});
});