├── package.json ├── database.json ├── README.md ├── database.sql └── server.js /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-api", 3 | "main": "server.js", 4 | "dependencies": { 5 | "express": "~4.0.0", 6 | "body-parser": "~1.0.1", 7 | "mysql": "~2.5.0", 8 | "sequelize": "~2.0.0", 9 | "crypto": "~0.0.3" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /database.json: -------------------------------------------------------------------------------- 1 | { 2 | "dev": { 3 | "driver": "mysql", 4 | "user": "root", 5 | "database": "tutorial", 6 | "password": "root" 7 | }, 8 | 9 | "production": { 10 | "driver": "mysql", 11 | "user": "root", 12 | "database": "myapp" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Tutorial 1: Node.js + Express 4 + MySQL 2 | === 3 | 4 | ### To install: 5 | 6 | ```sh 7 | sudo npm install 8 | ``` 9 | 10 | ### Database: 11 | Import the database structure from this file: database.json 12 | 13 | ### To execute: 14 | 15 | ```sh 16 | sudo node server.js 17 | ``` 18 | 19 | ### For more information: 20 | 21 | http://www.pabloanaya.com/blog/building-api-node-js-express-4-mysql 22 | 23 | 24 | -------------------------------------------------------------------------------- /database.sql: -------------------------------------------------------------------------------- 1 | SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; 2 | SET time_zone = "+00:00"; 3 | 4 | CREATE DATABASE `tutorial` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; 5 | USE `tutorial`; 6 | 7 | 8 | CREATE TABLE IF NOT EXISTS `users` ( 9 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 10 | `username` varchar(50) COLLATE utf8_unicode_ci NOT NULL, 11 | `password` varchar(200) COLLATE utf8_unicode_ci NOT NULL, 12 | PRIMARY KEY (`id`) 13 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; 14 | 15 | -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | // BASE SETUP 2 | // ============================================================================= 3 | 4 | var express = require('express'), 5 | bodyParser = require('body-parser'); 6 | 7 | var app = express(); 8 | app.use(bodyParser()); 9 | 10 | var env = app.get('env') == 'development' ? 'dev' : app.get('env'); 11 | var port = process.env.PORT || 8080; 12 | 13 | 14 | // IMPORT MODELS 15 | // ============================================================================= 16 | var Sequelize = require('sequelize'); 17 | 18 | // db config 19 | var env = "dev"; 20 | var config = require('./database.json')[env]; 21 | var password = config.password ? config.password : null; 22 | 23 | // initialize database connection 24 | var sequelize = new Sequelize( 25 | config.database, 26 | config.user, 27 | config.password, 28 | { 29 | dialect: config.driver, 30 | logging: console.log, 31 | define: { 32 | timestamps: false 33 | } 34 | } 35 | ); 36 | 37 | var crypto = require('crypto'); 38 | var DataTypes = require("sequelize"); 39 | 40 | var User = sequelize.define('users', { 41 | username: DataTypes.STRING, 42 | password: DataTypes.STRING 43 | }, { 44 | instanceMethods: { 45 | retrieveAll: function(onSuccess, onError) { 46 | User.findAll({}, {raw: true}).success(onSuccess).error(onError); 47 | }, 48 | retrieveById: function(user_id, onSuccess, onError) { 49 | User.find({where: {id: user_id}}, {raw: true}).success(onSuccess).error(onError); 50 | }, 51 | add: function(onSuccess, onError) { 52 | var username = this.username; 53 | var password = this.password; 54 | 55 | var shasum = crypto.createHash('sha1'); 56 | shasum.update(password); 57 | password = shasum.digest('hex'); 58 | 59 | User.build({ username: username, password: password }) 60 | .save().success(onSuccess).error(onError); 61 | }, 62 | updateById: function(user_id, onSuccess, onError) { 63 | var id = user_id; 64 | var username = this.username; 65 | var password = this.password; 66 | 67 | var shasum = crypto.createHash('sha1'); 68 | shasum.update(password); 69 | password = shasum.digest('hex'); 70 | 71 | User.update({ username: username,password: password},{where: {id: id} }).success(onSuccess).error(onError); 72 | }, 73 | removeById: function(user_id, onSuccess, onError) { 74 | User.destroy({where: {id: user_id}}).success(onSuccess).error(onError); 75 | } 76 | } 77 | }); 78 | 79 | 80 | // IMPORT ROUTES 81 | // ============================================================================= 82 | var router = express.Router(); 83 | 84 | // on routes that end in /users 85 | // ---------------------------------------------------- 86 | router.route('/users') 87 | 88 | // create a user (accessed at POST http://localhost:8080/api/users) 89 | .post(function(req, res) { 90 | 91 | var username = req.body.username; //bodyParser does the magic 92 | var password = req.body.password; 93 | 94 | var user = User.build({ username: username, password: password }); 95 | 96 | user.add(function(success){ 97 | res.json({ message: 'User created!' }); 98 | }, 99 | function(err) { 100 | res.send(err); 101 | }); 102 | }) 103 | 104 | // get all the users (accessed at GET http://localhost:8080/api/users) 105 | .get(function(req, res) { 106 | var user = User.build(); 107 | 108 | user.retrieveAll(function(users) { 109 | if (users) { 110 | res.json(users); 111 | } else { 112 | res.send(401, "User not found"); 113 | } 114 | }, function(error) { 115 | res.send("User not found"); 116 | }); 117 | }); 118 | 119 | 120 | // on routes that end in /users/:user_id 121 | // ---------------------------------------------------- 122 | router.route('/users/:user_id') 123 | 124 | // update a user (accessed at PUT http://localhost:8080/api/users/:user_id) 125 | .put(function(req, res) { 126 | var user = User.build(); 127 | 128 | user.username = req.body.username; 129 | user.password = req.body.password; 130 | 131 | user.updateById(req.params.user_id, function(success) { 132 | console.log(success); 133 | if (success) { 134 | res.json({ message: 'User updated!' }); 135 | } else { 136 | res.send(401, "User not found"); 137 | } 138 | }, function(error) { 139 | res.send("User not found"); 140 | }); 141 | }) 142 | 143 | // get a user by id(accessed at GET http://localhost:8080/api/users/:user_id) 144 | .get(function(req, res) { 145 | var user = User.build(); 146 | 147 | user.retrieveById(req.params.user_id, function(users) { 148 | if (users) { 149 | res.json(users); 150 | } else { 151 | res.send(401, "User not found"); 152 | } 153 | }, function(error) { 154 | res.send("User not found"); 155 | }); 156 | }) 157 | 158 | // delete a user by id (accessed at DELETE http://localhost:8080/api/users/:user_id) 159 | .delete(function(req, res) { 160 | var user = User.build(); 161 | 162 | user.removeById(req.params.user_id, function(users) { 163 | if (users) { 164 | res.json({ message: 'User removed!' }); 165 | } else { 166 | res.send(401, "User not found"); 167 | } 168 | }, function(error) { 169 | res.send("User not found"); 170 | }); 171 | }); 172 | 173 | // Middleware to use for all requests 174 | router.use(function(req, res, next) { 175 | // do logging 176 | console.log('Something is happening.'); 177 | next(); 178 | }); 179 | 180 | // REGISTER OUR ROUTES 181 | // ============================================================================= 182 | app.use('/api', router); 183 | 184 | // START THE SERVER 185 | // ============================================================================= 186 | app.listen(port); 187 | console.log('Magic happens on port ' + port); 188 | --------------------------------------------------------------------------------