├── app ├── config │ ├── env.js │ └── db.config.js ├── routers │ └── router.js ├── models │ └── customer.model.js └── controllers │ └── controller.js ├── package.json ├── server.js └── README.md /app/config/env.js: -------------------------------------------------------------------------------- 1 | const env = { 2 | database: 'loizenaidb', 3 | username: 'postgres', 4 | password: '123', 5 | host: 'localhost', 6 | dialect: 'postgres', 7 | pool: { 8 | max: 5, 9 | min: 0, 10 | acquire: 30000, 11 | idle: 10000 12 | } 13 | }; 14 | 15 | module.exports = env; -------------------------------------------------------------------------------- /app/routers/router.js: -------------------------------------------------------------------------------- 1 | let express = require('express'); 2 | let router = express.Router(); 3 | 4 | const customers = require('../controllers/controller.js'); 5 | 6 | router.post('/api/customer', customers.createCustomer); 7 | router.get('/api/customer/:id', customers.getCustomer); 8 | router.get('/api/customers', customers.customers); 9 | router.put('/api/customer', customers.updateCustomer); 10 | router.delete('/api/customer/:id', customers.deleteCustomer); 11 | 12 | module.exports = router; -------------------------------------------------------------------------------- /app/config/db.config.js: -------------------------------------------------------------------------------- 1 | const env = require('./env.js'); 2 | 3 | const Sequelize = require('sequelize'); 4 | const sequelize = new Sequelize(env.database, env.username, env.password, { 5 | host: env.host, 6 | dialect: env.dialect, 7 | operatorsAliases: false, 8 | 9 | pool: { 10 | max: env.max, 11 | min: env.pool.min, 12 | acquire: env.pool.acquire, 13 | idle: env.pool.idle 14 | } 15 | }); 16 | const db = {}; 17 | 18 | db.Sequelize = Sequelize; 19 | db.sequelize = sequelize; 20 | 21 | db.Customer = require('../models/customer.model.js')(sequelize, Sequelize); 22 | 23 | module.exports = db; -------------------------------------------------------------------------------- /app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const Customer = sequelize.define('customer', { 3 | id: { 4 | type: Sequelize.INTEGER, 5 | autoIncrement: true, 6 | primaryKey: true 7 | }, 8 | firstname: { 9 | type: Sequelize.STRING 10 | }, 11 | lastname: { 12 | type: Sequelize.STRING 13 | }, 14 | address: { 15 | type: Sequelize.STRING 16 | }, 17 | age: { 18 | type: Sequelize.INTEGER 19 | }, 20 | copyright: { 21 | type: Sequelize.STRING, 22 | defaultValue: "https://loizenai.com" 23 | } 24 | }); 25 | 26 | return Customer; 27 | } 28 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-reactjs-restapi-example", 3 | "version": "1.0.0", 4 | "description": "Nodejs Reactjs RestAPI CRUD MySQL database", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/loizenai" 12 | }, 13 | "keywords": [ 14 | "nodejs", 15 | "reactjs", 16 | "crud", 17 | "mysql" 18 | ], 19 | "author": "https://loizenai.com", 20 | "license": "ISC", 21 | "dependencies": { 22 | "body-parse": "^0.1.0", 23 | "cors": "^2.8.5", 24 | "express": "^4.17.1", 25 | "mysql2": "^2.2.5", 26 | "pg": "^8.4.2", 27 | "pg-hstore": "^2.3.3", 28 | "sequelize": "^6.3.5" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | var bodyParser = require('body-parser'); 5 | 6 | global.__basedir = __dirname; 7 | 8 | const db = require('./app/config/db.config.js'); 9 | 10 | const Customer = db.Customer; 11 | 12 | let router = require('./app/routers/router.js'); 13 | 14 | const cors = require('cors') 15 | const corsOptions = { 16 | origin: 'http://localhost:4200', 17 | optionsSuccessStatus: 200 18 | } 19 | app.use(cors(corsOptions)); 20 | 21 | app.use(bodyParser.json()); 22 | app.use(express.static('resources')); 23 | app.use('/', router); 24 | 25 | // Create a Server 26 | const server = app.listen(8080, function () { 27 | 28 | let host = server.address().address 29 | let port = server.address().port 30 | 31 | console.log("App listening at http://%s:%s", host, port); 32 | }) 33 | 34 | db.sequelize.sync({force: true}).then(() => { 35 | console.log('Drop and Resync with { force: true }'); 36 | Customer.sync().then(() => { 37 | const customers = [ 38 | { firstname: 'Jack', lastname: 'Smith', 39 | age: 23, address: '374 William S Canning Blvd'}, 40 | { firstname: 'Adam', lastname: 'Johnson', 41 | age: 31, address: 'Fall River MA 2721. 121 Worcester Rd'}, 42 | { firstname: 'Dana', lastname: 'Bay', 43 | age: 46, address: 'Framingham MA 1701. 677 Timpany Blvd'}, 44 | ] 45 | 46 | for(let i=0; i { 10 | let customer = {}; 11 | 12 | try{ 13 | // Building Customer object from upoading request's body 14 | customer.firstname = req.body.firstname; 15 | customer.lastname = req.body.lastname; 16 | customer.address = req.body.address; 17 | customer.age = req.body.age; 18 | 19 | // Save to MySQL database 20 | Customer.create(customer, 21 | {attributes: ['id', 'firstname', 'lastname', 'age', 'address', "copyright"]}) 22 | .then(result => { 23 | res.status(200).json(result); 24 | }); 25 | }catch(error){ 26 | res.status(500).json({ 27 | message: "Fail!", 28 | error: error.message 29 | }); 30 | } 31 | } 32 | 33 | /** 34 | * Retrieve Customer information from database 35 | * @param {*} req 36 | * @param {*} res 37 | */ 38 | exports.customers = (req, res) => { 39 | // find all Customer information from 40 | try{ 41 | Customer.findAll({attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyright']}) 42 | .then(customers => { 43 | res.status(200).json(customers); 44 | }) 45 | }catch(error) { 46 | // log on console 47 | console.log(error); 48 | 49 | res.status(500).json({ 50 | message: "Error!", 51 | error: error 52 | }); 53 | } 54 | } 55 | 56 | exports.getCustomer = (req, res) => { 57 | Customer.findByPk(req.params.id, 58 | {attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyright']}) 59 | .then(customer => { 60 | res.status(200).json(customer); 61 | }).catch(error => { 62 | // log on console 63 | console.log(error); 64 | 65 | res.status(500).json({ 66 | message: "Error!", 67 | error: error 68 | }); 69 | }) 70 | } 71 | 72 | /** 73 | * Updating a Customer 74 | * @param {*} req 75 | * @param {*} res 76 | */ 77 | exports.updateCustomer = async (req, res) => { 78 | try{ 79 | let customer = await Customer.findByPk(req.body.id); 80 | 81 | if(!customer){ 82 | // return a response to client 83 | res.status(404).json({ 84 | message: "Not Found for updating a customer with id = " + customerId, 85 | error: "404" 86 | }); 87 | } else { 88 | // update new change to database 89 | let updatedObject = { 90 | firstname: req.body.firstname, 91 | lastname: req.body.lastname, 92 | address: req.body.address, 93 | age: req.body.age 94 | } 95 | let result = await Customer.update(updatedObject, 96 | { 97 | returning: true, 98 | where: {id: req.body.id}, 99 | attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyright'] 100 | } 101 | ); 102 | 103 | // return the response to client 104 | if(!result) { 105 | res.status(500).json({ 106 | message: "Error -> Can not update a customer with id = " + req.params.id, 107 | error: "Can NOT Updated", 108 | }); 109 | } 110 | 111 | res.status(200).json(result); 112 | } 113 | } catch(error){ 114 | res.status(500).json({ 115 | message: "Error -> Can not update a customer with id = " + req.params.id, 116 | error: error.message 117 | }); 118 | } 119 | } 120 | 121 | /** 122 | * Delete a Customer by ID 123 | * @param {*} req 124 | * @param {*} res 125 | */ 126 | exports.deleteCustomer = async (req, res) => { 127 | try{ 128 | let customerId = req.params.id; 129 | let customer = await Customer.findByPk(customerId); 130 | 131 | if(!customer){ 132 | res.status(404).json({ 133 | message: "Does Not exist a Customer with id = " + customerId, 134 | error: "404", 135 | }); 136 | } else { 137 | await customer.destroy(); 138 | res.status(200); 139 | } 140 | } catch(error) { 141 | res.status(500).json({ 142 | message: "Error -> Can NOT delete a customer with id = " + req.params.id, 143 | error: error.message 144 | }); 145 | } 146 | } --------------------------------------------------------------------------------