|
| 1 | +const express = require('express'); |
| 2 | +const mysql = require('mysql'); |
| 3 | + |
| 4 | +const bodyParser = require('body-parser'); |
| 5 | + |
| 6 | +const PORT = process.env.PORT || 3050; |
| 7 | + |
| 8 | +const app = express(); |
| 9 | + |
| 10 | +app.use(bodyParser.json()); |
| 11 | + |
| 12 | +// MySql |
| 13 | +const connection = mysql.createConnection({ |
| 14 | + host: 'localhost', |
| 15 | + user: 'root', |
| 16 | + password: 'rootpass', |
| 17 | + database: 'node20_mysql' |
| 18 | +}); |
| 19 | + |
| 20 | +// Route |
| 21 | +app.get('/', (req, res) => { |
| 22 | + res.send('Welcome to my API!'); |
| 23 | +}); |
| 24 | + |
| 25 | +// all customers |
| 26 | +app.get('/customers', (req, res) => { |
| 27 | + const sql = 'SELECT * FROM customers'; |
| 28 | + |
| 29 | + connection.query(sql, (error, results) => { |
| 30 | + if (error) throw error; |
| 31 | + if (results.length > 0) { |
| 32 | + res.json(results); |
| 33 | + } else { |
| 34 | + res.send('Not result'); |
| 35 | + } |
| 36 | + }); |
| 37 | +}); |
| 38 | + |
| 39 | +app.get('/customers/:id', (req, res) => { |
| 40 | + const { id } = req.params; |
| 41 | + const sql = `SELECT * FROM customers WHERE id = ${id}`; |
| 42 | + connection.query(sql, (error, result) => { |
| 43 | + if (error) throw error; |
| 44 | + |
| 45 | + if (result.length > 0) { |
| 46 | + res.json(result); |
| 47 | + } else { |
| 48 | + res.send('Not result'); |
| 49 | + } |
| 50 | + }); |
| 51 | +}); |
| 52 | + |
| 53 | +app.post('/add', (req, res) => { |
| 54 | + const sql = 'INSERT INTO customers SET ?'; |
| 55 | + |
| 56 | + const customerObj = { |
| 57 | + name: req.body.name, |
| 58 | + city: req.body.city |
| 59 | + }; |
| 60 | + |
| 61 | + connection.query(sql, customerObj, error => { |
| 62 | + if (error) throw error; |
| 63 | + res.send('Customer created!'); |
| 64 | + }); |
| 65 | +}); |
| 66 | + |
| 67 | +app.put('/update/:id', (req, res) => { |
| 68 | + const { id } = req.params; |
| 69 | + const { name, city } = req.body; |
| 70 | + const sql = `UPDATE customers SET name = '${name}', city='${city}' WHERE id =${id}`; |
| 71 | + |
| 72 | + connection.query(sql, error => { |
| 73 | + if (error) throw error; |
| 74 | + res.send('Customer updated!'); |
| 75 | + }); |
| 76 | +}); |
| 77 | + |
| 78 | +app.delete('/delete/:id', (req, res) => { |
| 79 | + const { id } = req.params; |
| 80 | + const sql = `DELETE FROM customers WHERE id= ${id}`; |
| 81 | + |
| 82 | + connection.query(sql, error => { |
| 83 | + if (error) throw error; |
| 84 | + res.send('Delete customer'); |
| 85 | + }); |
| 86 | +}); |
| 87 | + |
| 88 | +// Check connect |
| 89 | +connection.connect(error => { |
| 90 | + if (error) throw error; |
| 91 | + console.log('Database server running!'); |
| 92 | +}); |
| 93 | + |
| 94 | +app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); |
0 commit comments