· 6 years ago · Jun 14, 2019, 03:20 AM
1const mysql = require('mysql');
2
3/* OLD CONNECTION - we don't need this anymore */
4// const connection = mysql.createConnection({
5// host: 'localhost',
6// user: 'root',
7// password: 'password',
8// database: 'some_database'
9// });
10
11/* NEW CONNECTION - this works for docker-compose! */
12const connection = mysql.createConnection('mysql://root:password@database:3306/some_database');
13
14connection.connect();
15
16// Delete the table if it exists
17connection.query(`DROP TABLE IF EXISTS some_table`);
18
19// Create the table
20connection.query(`CREATE TABLE some_table (
21 id INT NOT NULL AUTO_INCREMENT,
22 attribute VARCHAR(255) NOT NULL,
23 PRIMARY KEY(id)
24 );`);
25
26// Seed the database with some values
27const values = [['a'], ['b'], ['c']]
28connection.query(`INSERT INTO some_table(attribute) VALUES ?`, [values]);
29
30// Controller function to pass data into callback
31const getData = (id, callback) => {
32 connection.query(`SELECT * FROM some_table where id = ${id}`, (err, data) => {
33 if (err) {
34 return callback(err);
35 }
36 callback(data);
37 });
38}
39
40// Export the function so it's available to our server
41module.exports = {
42 getData
43}