Design a solid MVC REST API with node.js express and ORM Part 2

  • GET /users — Get all users (collection resource)
  • GET /users/{id} — Get one user (singleton resource)
Photo by XPS on Unsplash
const usersData = {...}
exports.getUser = (req, res, next) => {
const id = req.params.userId;
if (id && usersData[id]) {
res.json(usersData[id]);
res.status(200).send();
} else {
// Not Found
res.status(404).send();
}
};
// to retrieve resource
exports.getAll = (req, res, next) => {
// Respond with some data and return status OK
res.json(usersData);
res.status(200).send();
};
// to create new resources
exports.createUser = (req, res, next) => {
// Return our request body and return status OK
res.json(req.body).status(200).send();
};
// routes/users.js
const userController = require('../controllers/user-controller');

router.route('/users')
.get(userController.getAll);

router.route('/users/:userId')
.get(userController.getUser)

Database and ORM

npm install --save sequelize
npm install --save sqlite3
// db/sequilize.js// Example for sqlite
const sequelize = new Sequelize('sqlite::memory:')
// models/user.jsconst { DataTypes } = require('sequelize');module.exports = (sequelize) => {
sequelize.define('user', {
id: {
type: DataTypes.BIGINT(20),
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING(50),
allowNull: false,
validate: {
min: {
args: 2,
},
max: {
args: 50,
}
}
},
email: {
type: DataTypes.STRING(60),
validate: {
isEmail: true
}
}
});
};
const { Sequelize } = require('sequelize');// Example for sqlite
const sequelize = new Sequelize('sqlite::memory:')
const models = [
// Add here all of your models
require('../models/user'),
].map(m=>m(sequelize));
sequelize.sync().then(console.log('DB is synced'));module.exports = sequelize;
exports.getAll = (req, res, next) => {
models.user.findAll().then(users => {
res.json(users)
}).catch(next);
};
exports.get = async (req, res, next) => {
const id = req.params.userId;
const user = await models.user.findByPk(id)
.catch(next);
if(user) {
res.json(user);
} else {
res.status(404).send(`User with id ${id} not found!`);
}
};
exports.create = (req, res, next) => {
models.user.create(req.body).then(u => res.json(u))
.catch(next);
};
exports.update = (req, res, next) => {
const newUser = req.body;
const id = req.params.userId;
models.user.findByPk(id).then(async (user) => {
if (user) {
await models.user.update(newUser, {where: {id}})
res.status(200).send()
}else {
res.status(404).send();
}
}).catch(next);
};
exports.deleteUser = (req, res, next) => {
const id = req.params.userId;
models.user.destroy({where:{id}}).then(res.status(200).send()).catch(next);
};
const router = require('express').Router();
const userController = require('../controllers/user-controller');
router.route('/users')
.post(userController.create) // to create new subordinate resources
.get(userController.getAll); // to retrieve resource representation/information only
router.route('/users/:userId')
.get(userController.get) // to retrieve resource representation/information only
.put(userController.update) // to update existing resource
.delete(userController.deleteUser) // to delete resources
module.exports = router;

--

--

--

Software Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Understanding of DOM(Document Object Model), Shadow DOM, Virtual DOM.

Tip #33[truncating text]

Best Practices for Node.js apps

The Basics of React

Angular pipe

Retry pattern to make your app more resilient | Apiumhub

Unsend Recall for Messenger — Recalling removed messages in Facebook Messenger

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Elia Bar

Elia Bar

Software Developer

More from Medium

Node.js MySQL Create Database

Create events on Google calendar using Google Calendar API in Node.js

API design 101 : build a nodejs REST microservice using GITHUB APIs

Parsing site with Node JS