├── .gitignore ├── .sequelizerc ├── README.md ├── index.js ├── package.json └── server ├── config └── config.json ├── controller ├── index.js ├── post.js └── user.js ├── migrations ├── acreate-user.js └── create-post.js ├── models ├── index.js ├── post.js └── user.js └── routes └── index.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | 3 | package-lock.json -------------------------------------------------------------------------------- /.sequelizerc: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | module.exports = { 4 | "config": path.resolve('./server/config', 'config.json'), 5 | "models-path": path.resolve('./server/models'), 6 | "seeders-path": path.resolve('./server/seeders'), 7 | "migrations-path": path.resolve('./server/migrations') 8 | }; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Building REST API in Node/Express App using Sequelize,Postgres 2 | 3 | This Repository is building REST API Design in Node/Express App using Sequelize and Postgres. 4 | 5 | ### PreRequisites 6 | - [Postgres](https://www.postgresql.org/download/) 7 | - [Node](https://nodejs.org/en/download/) 8 | 9 | ### Setup 10 | ``` 11 | $ npm install 12 | $ node_modules/.bin/sequelize init 13 | ``` 14 | Sequelize init will creat a folder `config`,`controller`,`migrations` and `models` 15 | 16 | create a file called `.sequelizerc` 17 | ``` 18 | const path = require('path'); 19 | 20 | module.exports = { 21 | "config": path.resolve('./server/config', 'config.json'), 22 | "models-path": path.resolve('./server/models'), 23 | "seeders-path": path.resolve('./server/seeders'), 24 | "migrations-path": path.resolve('./server/migrations') 25 | }; 26 | ``` 27 | 28 | Create a Database `testdb` in Postgres Dashboard 29 | 30 | ``` 31 | $ node_modules/.bin/sequelize db:migrate 32 | ``` 33 | 34 | #### To Run Application 35 | 36 | ``` 37 | $ node index.js 38 | ``` -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const bodyParser = require('body-parser'); 3 | const app = express(); 4 | 5 | app.use(bodyParser.json()); 6 | app.use(bodyParser.urlencoded({extended : false})); 7 | 8 | require('./server/routes')(app); 9 | 10 | const PORT = 3456; 11 | app.listen(PORT,() => { 12 | console.log(`Server is listening to port ${PORT}`) 13 | }) -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-sequelize", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "dev" : "node index.js", 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "keywords": [], 11 | "author": "", 12 | "license": "ISC", 13 | "dependencies": { 14 | "body-parser": "^1.19.0", 15 | "express": "^4.17.1", 16 | "pg": "^7.12.1", 17 | "pg-hstore": "^2.3.3", 18 | "sequelize": "4.38.1", 19 | "sequelize-cli": "^4.1.1" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /server/config/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "development": { 3 | "username": "postgres", 4 | "password": 123456, 5 | "database": "testdb", 6 | "host": "127.0.0.1", 7 | "port" : 5432, 8 | "dialect": "postgres" 9 | }, 10 | "test": { 11 | "username": "root", 12 | "password": null, 13 | "database": "database_test", 14 | "host": "127.0.0.1", 15 | "dialect": "mysql", 16 | "operatorsAliases": false 17 | }, 18 | "production": { 19 | "username": "root", 20 | "password": null, 21 | "database": "database_production", 22 | "host": "127.0.0.1", 23 | "dialect": "mysql", 24 | "operatorsAliases": false 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /server/controller/index.js: -------------------------------------------------------------------------------- 1 | const post = require('./post'); 2 | const user = require('./user'); 3 | 4 | module.exports = { 5 | post, 6 | user 7 | } -------------------------------------------------------------------------------- /server/controller/post.js: -------------------------------------------------------------------------------- 1 | const Post = require('../models').Post; 2 | const User = require('../models').User; 3 | 4 | module.exports = { 5 | 6 | async getAllPostsOfUser(req,res) { 7 | try { 8 | const userCollection = await User.find({ 9 | id : req.params.userId 10 | }); 11 | 12 | if(userCollection){ 13 | const postCollection = await Post.find({ 14 | userId : req.params.userId 15 | }) 16 | 17 | res.status(201).send(postCollection); 18 | } 19 | else{ 20 | re.status(404).send("User Not Found") 21 | } 22 | } 23 | catch(e){ 24 | console.log(e); 25 | res.status(500).send(e); 26 | } 27 | 28 | }, 29 | 30 | async createPost(req,res) { 31 | 32 | try { 33 | const post = await Post.create({ 34 | title : req.body.title, 35 | userId : req.body.userId 36 | }); 37 | res.status(201).send(post) 38 | } 39 | catch(e){ 40 | console.log(e); 41 | res.status(400).send(e); 42 | } 43 | }, 44 | 45 | async update(req,res) { 46 | try{ 47 | const postCollection = await Post.find({ 48 | id : req.params.postId 49 | }); 50 | 51 | if(postCollection){ 52 | const updatedPost = await postCollection.update({ 53 | title : req.body.title 54 | }) 55 | 56 | res.status(201).send(updatedPost); 57 | } 58 | else{ 59 | res.status(404).send("Post Not Found"); 60 | } 61 | 62 | } 63 | catch(e){ 64 | console.log(e); 65 | res.status(400).send(e); 66 | } 67 | 68 | } 69 | } -------------------------------------------------------------------------------- /server/controller/user.js: -------------------------------------------------------------------------------- 1 | const User = require('../models').User; 2 | 3 | module.exports = { 4 | 5 | async getAllUsers(req,res) { 6 | 7 | try { 8 | 9 | const userCollection = await User.find({}); 10 | 11 | res.status(201).send(userCollection); 12 | 13 | } 14 | catch(e){ 15 | console.log(e); 16 | 17 | res.status(500).send(e); 18 | } 19 | 20 | }, 21 | 22 | async create(req,res) { 23 | try { 24 | const userCollection = await User 25 | .create({ 26 | email : req.body.email, 27 | }); 28 | 29 | res.status(201).send(userCollection); 30 | } 31 | catch(e){ 32 | console.log(e); 33 | res.status(400).send(e); 34 | } 35 | 36 | }, 37 | 38 | async update(req,res) { 39 | 40 | try{ 41 | const userCollection = await User.find({ 42 | id : req.params.userId 43 | }); 44 | 45 | if(userCollection){ 46 | 47 | const updatedUser = await User.update({ 48 | id : req.body.email 49 | }); 50 | 51 | res.status(201).send(updatedUser) 52 | 53 | } 54 | else{ 55 | 56 | res.status(404).send("User Not Found"); 57 | } 58 | 59 | } 60 | catch(e){ 61 | console.log(e); 62 | 63 | res.status(500).send(e); 64 | 65 | } 66 | } 67 | 68 | 69 | } -------------------------------------------------------------------------------- /server/migrations/acreate-user.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | up: (queryInterface, Sequelize) => 3 | queryInterface.createTable('Users', { 4 | id: { 5 | allowNull: false, 6 | autoIncrement: true, 7 | primaryKey: true, 8 | type: Sequelize.INTEGER, 9 | }, 10 | email: { 11 | type: Sequelize.STRING, 12 | allowNull: false, 13 | }, 14 | createdAt: { 15 | allowNull: false, 16 | type: Sequelize.DATE, 17 | }, 18 | updatedAt: { 19 | allowNull: false, 20 | type: Sequelize.DATE, 21 | }, 22 | }), 23 | down: (queryInterface /* , Sequelize */) => queryInterface.dropTable('Users'), 24 | }; -------------------------------------------------------------------------------- /server/migrations/create-post.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | up: (queryInterface, Sequelize) => 3 | queryInterface.createTable('Posts', { 4 | id: { 5 | allowNull: false, 6 | autoIncrement: true, 7 | primaryKey: true, 8 | type: Sequelize.INTEGER, 9 | }, 10 | title: { 11 | type: Sequelize.STRING, 12 | allowNull: false, 13 | }, 14 | userId : { 15 | type : Sequelize.INTEGER, 16 | onDelete : 'CASCADE', 17 | references : { 18 | model : 'Users', 19 | key : 'id', 20 | as : 'userId' 21 | }, 22 | }, 23 | createdAt: { 24 | allowNull: false, 25 | type: Sequelize.DATE, 26 | }, 27 | updatedAt: { 28 | allowNull: false, 29 | type: Sequelize.DATE, 30 | }, 31 | }), 32 | down: (queryInterface /* , Sequelize */) => queryInterface.dropTable('Posts'), 33 | }; -------------------------------------------------------------------------------- /server/models/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | const Sequelize = require('sequelize'); 6 | const basename = path.basename(__filename); 7 | const env = process.env.NODE_ENV || 'development'; 8 | const config = require(__dirname + '/../config/config.json')[env]; 9 | const db = {}; 10 | 11 | let sequelize; 12 | if (config.use_env_variable) { 13 | sequelize = new Sequelize(process.env[config.use_env_variable], config); 14 | } else { 15 | sequelize = new Sequelize(config.database, config.username, config.password, config); 16 | } 17 | 18 | fs 19 | .readdirSync(__dirname) 20 | .filter(file => { 21 | return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'); 22 | }) 23 | .forEach(file => { 24 | const model = sequelize['import'](path.join(__dirname, file)); 25 | db[model.name] = model; 26 | }); 27 | 28 | Object.keys(db).forEach(modelName => { 29 | if (db[modelName].associate) { 30 | db[modelName].associate(db); 31 | } 32 | }); 33 | 34 | db.sequelize = sequelize; 35 | db.Sequelize = Sequelize; 36 | 37 | module.exports = db; 38 | -------------------------------------------------------------------------------- /server/models/post.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | module.exports = (sequelize,DataTypes) => { 4 | let Post = sequelize.define('Post',{ 5 | title : DataTypes.STRING 6 | }); 7 | 8 | Post.associate = function (models) { 9 | Post.belongsTo(models.User,{ 10 | onDelete : "CASCADE", 11 | foreignKey : 'userId' 12 | }); 13 | }; 14 | 15 | return Post; 16 | } -------------------------------------------------------------------------------- /server/models/user.js: -------------------------------------------------------------------------------- 1 | 2 | module.exports = (sequelize,DataTypes) => { 3 | let User = sequelize.define('User',{ 4 | email : DataTypes.STRING 5 | }); 6 | 7 | User.associate = function(models) { 8 | User.hasMany(models.Post,{ 9 | foreignKey : 'userId', 10 | as : 'posts' 11 | }); 12 | }; 13 | return User; 14 | } -------------------------------------------------------------------------------- /server/routes/index.js: -------------------------------------------------------------------------------- 1 | const userController = require('../controller').user; 2 | const postController = require('../controller').post; 3 | module.exports = (app) => { 4 | 5 | app.get('/api',(req,res) => { 6 | res.status(200).send({ 7 | data : "Welcome Node Sequlize API v1" 8 | }) 9 | }) 10 | 11 | app.get('/api/users',userController.getAllUsers); 12 | 13 | app.post('/api/user/create',userController.create); 14 | 15 | app.put('/api/user/:userId',userController.update); 16 | 17 | app.get('/api/:userId/posts',postController.getAllPostsOfUser); 18 | 19 | app.post('/api/post/create',postController.createPost); 20 | 21 | app.put('/api/:postId',postController.update); 22 | 23 | } --------------------------------------------------------------------------------