├── _helpers ├── role.js └── db.js ├── README.md ├── config.json ├── _middleware ├── error-handler.js └── validate-request.js ├── package.json ├── server.js ├── .gitignore ├── users ├── user.model.js ├── user.service.js └── users.controller.js └── LICENSE /_helpers/role.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | Admin: 'Admin', 3 | User: 'User' 4 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # node-mysql-crud-api 2 | 3 | Node.js + MySQL - CRUD API Example 4 | 5 | Documentation and instructions available at https://jasonwatmore.com/post/2021/11/22/nodejs-mysql-crud-api-example-and-tutorial -------------------------------------------------------------------------------- /config.json: -------------------------------------------------------------------------------- 1 | { 2 | "database": { 3 | "host": "localhost", 4 | "port": 3306, 5 | "user": "root", 6 | "password": "", 7 | "database": "node-mysql-crud-api" 8 | } 9 | } -------------------------------------------------------------------------------- /_middleware/error-handler.js: -------------------------------------------------------------------------------- 1 | module.exports = errorHandler; 2 | 3 | function errorHandler(err, req, res, next) { 4 | switch (true) { 5 | case typeof err === 'string': 6 | // custom application error 7 | const is404 = err.toLowerCase().endsWith('not found'); 8 | const statusCode = is404 ? 404 : 400; 9 | return res.status(statusCode).json({ message: err }); 10 | default: 11 | return res.status(500).json({ message: err.message }); 12 | } 13 | } -------------------------------------------------------------------------------- /_middleware/validate-request.js: -------------------------------------------------------------------------------- 1 | module.exports = validateRequest; 2 | 3 | function validateRequest(req, next, schema) { 4 | const options = { 5 | abortEarly: false, // include all errors 6 | allowUnknown: true, // ignore unknown props 7 | stripUnknown: true // remove unknown props 8 | }; 9 | const { error, value } = schema.validate(req.body, options); 10 | if (error) { 11 | next(`Validation error: ${error.details.map(x => x.message).join(', ')}`); 12 | } else { 13 | req.body = value; 14 | next(); 15 | } 16 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-mysql-crud-api", 3 | "version": "1.0.0", 4 | "license": "MIT", 5 | "scripts": { 6 | "start": "node ./server.js", 7 | "start:dev": "nodemon ./server.js" 8 | }, 9 | "dependencies": { 10 | "bcryptjs": "^2.4.3", 11 | "cors": "^2.8.5", 12 | "express": "^4.17.1", 13 | "joi": "^17.2.0", 14 | "mysql2": "^2.1.0", 15 | "rootpath": "^0.1.2", 16 | "sequelize": "^6.3.4" 17 | }, 18 | "devDependencies": { 19 | "nodemon": "^2.0.4" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | require('rootpath')(); 2 | const express = require('express'); 3 | const app = express(); 4 | const cors = require('cors'); 5 | const errorHandler = require('_middleware/error-handler'); 6 | 7 | app.use(express.json()); 8 | app.use(express.urlencoded({ extended: true })); 9 | app.use(cors()); 10 | 11 | // api routes 12 | app.use('/users', require('./users/users.controller')); 13 | 14 | // global error handler 15 | app.use(errorHandler); 16 | 17 | // start server 18 | const port = process.env.NODE_ENV === 'production' ? (process.env.PORT || 80) : 4000; 19 | app.listen(port, () => console.log('Server listening on port ' + port)); -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release 28 | 29 | # Dependency directories 30 | node_modules 31 | jspm_packages 32 | typings 33 | 34 | # Optional npm cache directory 35 | .npm 36 | 37 | # Optional REPL history 38 | .node_repl_history -------------------------------------------------------------------------------- /_helpers/db.js: -------------------------------------------------------------------------------- 1 | const config = require('config.json'); 2 | const mysql = require('mysql2/promise'); 3 | const { Sequelize } = require('sequelize'); 4 | 5 | module.exports = db = {}; 6 | 7 | initialize(); 8 | 9 | async function initialize() { 10 | // create db if it doesn't already exist 11 | const { host, port, user, password, database } = config.database; 12 | const connection = await mysql.createConnection({ host, port, user, password }); 13 | await connection.query(`CREATE DATABASE IF NOT EXISTS \`${database}\`;`); 14 | 15 | // connect to db 16 | const sequelize = new Sequelize(database, user, password, { dialect: 'mysql' }); 17 | 18 | // init models and add them to the exported db object 19 | db.User = require('../users/user.model')(sequelize); 20 | 21 | // sync all models with database 22 | await sequelize.sync({ alter: true }); 23 | } -------------------------------------------------------------------------------- /users/user.model.js: -------------------------------------------------------------------------------- 1 | const { DataTypes } = require('sequelize'); 2 | 3 | module.exports = model; 4 | 5 | function model(sequelize) { 6 | const attributes = { 7 | email: { type: DataTypes.STRING, allowNull: false }, 8 | passwordHash: { type: DataTypes.STRING, allowNull: false }, 9 | title: { type: DataTypes.STRING, allowNull: false }, 10 | firstName: { type: DataTypes.STRING, allowNull: false }, 11 | lastName: { type: DataTypes.STRING, allowNull: false }, 12 | role: { type: DataTypes.STRING, allowNull: false } 13 | }; 14 | 15 | const options = { 16 | defaultScope: { 17 | // exclude password hash by default 18 | attributes: { exclude: ['passwordHash'] } 19 | }, 20 | scopes: { 21 | // include hash with this scope 22 | withHash: { attributes: {}, } 23 | } 24 | }; 25 | 26 | return sequelize.define('User', attributes, options); 27 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2021 Jason Watmore 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /users/user.service.js: -------------------------------------------------------------------------------- 1 | const bcrypt = require('bcryptjs'); 2 | const db = require('_helpers/db'); 3 | 4 | module.exports = { 5 | getAll, 6 | getById, 7 | create, 8 | update, 9 | delete: _delete 10 | }; 11 | 12 | async function getAll() { 13 | return await db.User.findAll(); 14 | } 15 | 16 | async function getById(id) { 17 | return await getUser(id); 18 | } 19 | 20 | async function create(params) { 21 | // validate 22 | if (await db.User.findOne({ where: { email: params.email } })) { 23 | throw 'Email "' + params.email + '" is already registered'; 24 | } 25 | 26 | const user = new db.User(params); 27 | 28 | // hash password 29 | user.passwordHash = await bcrypt.hash(params.password, 10); 30 | 31 | // save user 32 | await user.save(); 33 | } 34 | 35 | async function update(id, params) { 36 | const user = await getUser(id); 37 | 38 | // validate 39 | const emailChanged = params.email && user.email !== params.email; 40 | if (emailChanged && await db.User.findOne({ where: { email: params.email } })) { 41 | throw 'Email "' + params.email + '" is already registered'; 42 | } 43 | 44 | // hash password if it was entered 45 | if (params.password) { 46 | params.passwordHash = await bcrypt.hash(params.password, 10); 47 | } 48 | 49 | // copy params to user and save 50 | Object.assign(user, params); 51 | await user.save(); 52 | } 53 | 54 | async function _delete(id) { 55 | const user = await getUser(id); 56 | await user.destroy(); 57 | } 58 | 59 | // helper functions 60 | 61 | async function getUser(id) { 62 | const user = await db.User.findByPk(id); 63 | if (!user) throw 'User not found'; 64 | return user; 65 | } 66 | -------------------------------------------------------------------------------- /users/users.controller.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const router = express.Router(); 3 | const Joi = require('joi'); 4 | const validateRequest = require('_middleware/validate-request'); 5 | const Role = require('_helpers/role'); 6 | const userService = require('./user.service'); 7 | 8 | // routes 9 | 10 | router.get('/', getAll); 11 | router.get('/:id', getById); 12 | router.post('/', createSchema, create); 13 | router.put('/:id', updateSchema, update); 14 | router.delete('/:id', _delete); 15 | 16 | module.exports = router; 17 | 18 | // route functions 19 | 20 | function getAll(req, res, next) { 21 | userService.getAll() 22 | .then(users => res.json(users)) 23 | .catch(next); 24 | } 25 | 26 | function getById(req, res, next) { 27 | userService.getById(req.params.id) 28 | .then(user => res.json(user)) 29 | .catch(next); 30 | } 31 | 32 | function create(req, res, next) { 33 | userService.create(req.body) 34 | .then(() => res.json({ message: 'User created' })) 35 | .catch(next); 36 | } 37 | 38 | function update(req, res, next) { 39 | userService.update(req.params.id, req.body) 40 | .then(() => res.json({ message: 'User updated' })) 41 | .catch(next); 42 | } 43 | 44 | function _delete(req, res, next) { 45 | userService.delete(req.params.id) 46 | .then(() => res.json({ message: 'User deleted' })) 47 | .catch(next); 48 | } 49 | 50 | // schema functions 51 | 52 | function createSchema(req, res, next) { 53 | const schema = Joi.object({ 54 | title: Joi.string().required(), 55 | firstName: Joi.string().required(), 56 | lastName: Joi.string().required(), 57 | role: Joi.string().valid(Role.Admin, Role.User).required(), 58 | email: Joi.string().email().required(), 59 | password: Joi.string().min(6).required(), 60 | confirmPassword: Joi.string().valid(Joi.ref('password')).required() 61 | }); 62 | validateRequest(req, next, schema); 63 | } 64 | 65 | function updateSchema(req, res, next) { 66 | const schema = Joi.object({ 67 | title: Joi.string().empty(''), 68 | firstName: Joi.string().empty(''), 69 | lastName: Joi.string().empty(''), 70 | role: Joi.string().valid(Role.Admin, Role.User).empty(''), 71 | email: Joi.string().email().empty(''), 72 | password: Joi.string().min(6).empty(''), 73 | confirmPassword: Joi.string().valid(Joi.ref('password')).empty('') 74 | }).with('password', 'confirmPassword'); 75 | validateRequest(req, next, schema); 76 | } 77 | --------------------------------------------------------------------------------