<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: VitaliiKulyk</title>
    <description>The latest articles on DEV Community by VitaliiKulyk (@vitaliikulyk).</description>
    <link>https://dev.to/vitaliikulyk</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F62235%2F995eeb6d-0098-4310-ac00-e71eebb60f84.jpg</url>
      <title>DEV Community: VitaliiKulyk</title>
      <link>https://dev.to/vitaliikulyk</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/vitaliikulyk"/>
    <language>en</language>
    <item>
      <title>How to Initialize Multilayer Node.js RESTful API with JWT Auth and PostgreSQL in 3 Steps</title>
      <dc:creator>VitaliiKulyk</dc:creator>
      <pubDate>Tue, 13 Mar 2018 11:53:19 +0000</pubDate>
      <link>https://dev.to/vitaliikulyk/how-to-initialize-multilayer-nodejs-restful-api-with-jwt-auth-and-postgresql-in-3-steps--c8c</link>
      <guid>https://dev.to/vitaliikulyk/how-to-initialize-multilayer-nodejs-restful-api-with-jwt-auth-and-postgresql-in-3-steps--c8c</guid>
      <description>

&lt;p id="e7a1" class="graf graf--p graf-after--p"&gt;It’s a little-known fact that when Julius Caesar delivered his famous quote “Divide and conquer,” he was actually talking about using layered architecture for building web applications. Its principle lies in separating the user interface from the business logic and the business logic from the data access logic. Layered architecture offers increased flexibility, maintainability and scalability, plus it’s easier to write, test and maintain. Sounds good but how can you implement it using modern technologies?&lt;/p&gt;
&lt;p id="c1fe" class="graf graf--p graf-after--p"&gt;For those of you who are new to Node.js and RESTful API, we’ve written a how-to guide that will help you create a RESTful API that can be developed into a large service. In this tutorial, we’ll show you how to start building a RESTful API in three steps. The JSON Web Token technique will help us handle authentication and PostgreSQL will be our database.&lt;/p&gt;
&lt;p id="7380" class="graf graf--p graf-after--p"&gt;So, our steps to writing a RESTful API are:&lt;/p&gt;
&lt;ol class="postList"&gt;
&lt;li id="f997" class="graf graf--li graf-after--p"&gt;Initializing a Node.js project&lt;/li&gt;
&lt;li id="3923" class="graf graf--li graf-after--li"&gt;JWT authentication&lt;/li&gt;
&lt;li id="4315" class="graf graf--li graf-after--li"&gt;Adding layers&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="0211" class="graf graf--h3 graf-after--li"&gt;Initializing a Node.js project&lt;/h3&gt;
&lt;p id="9ef6" class="graf graf--p graf-after--h3"&gt;Let’s start building our application. Create an empty folder and initialize a new project with the following command:npm init&lt;/p&gt;
&lt;p id="182d" class="graf graf--p graf-after--p"&gt;To install the necessary packages, run the command:npm i bcrypt bluebird body-parser express http jsonwebtoken lodash pg sequelize sequelize-values — save&lt;/p&gt;
&lt;p id="88c5" class="graf graf--p graf-after--p"&gt;Next, create the following files in the main folder:&lt;/p&gt;
&lt;ul class="postList"&gt;
&lt;li id="4b4b" class="graf graf--li graf-after--p"&gt;
&lt;strong class="markup--strong markup--li-strong"&gt;config.js&lt;/strong&gt; (the application’s configuration like database connections, password salts, etc.)&lt;/li&gt;
&lt;li id="fecb" class="graf graf--li graf-after--li"&gt;
&lt;strong class="markup--strong markup--li-strong"&gt;db.js&lt;/strong&gt; (responsible for the database connection)&lt;/li&gt;
&lt;li id="612d" class="graf graf--li graf-after--li"&gt;
&lt;strong class="markup--strong markup--li-strong"&gt;router.js&lt;/strong&gt; (handles http requests and dispatches them to controllers)&lt;/li&gt;
&lt;li id="84a3" class="graf graf--li graf-after--li"&gt;
&lt;strong class="markup--strong markup--li-strong"&gt;index.js&lt;/strong&gt; — (a startup file)&lt;/li&gt;
&lt;/ul&gt;
&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Su8Mr6cs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/freeze/max/38/0%2Aj03M1BM5BkOMP91K.%3Fq%3D20" class="progressiveMedia-thumbnail js-progressiveMedia-thumbnail"&gt;&lt;img class="progressiveMedia-image js-progressiveMedia-image"&gt;&lt;img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://res.cloudinary.com/practicaldev/image/fetch/s--Ih0FyqKz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1000/0%2Aj03M1BM5BkOMP91K."&gt;&lt;p id="b811" class="graf graf--p graf-after--figure"&gt;Here’s the code our files contain:&lt;/p&gt;
&lt;h4 id="0223" class="graf graf--h4 graf-after--p"&gt;config.js:&lt;/h4&gt;
&lt;pre id="2b1d" class="graf graf--pre graf-after--h4"&gt;module.exports = {&lt;br&gt;     port: 3000,&lt;br&gt;     dbConnectionString: 'your postgresql connection',&lt;br&gt;     saltRounds: 2,&lt;br&gt;     jwtSecret: 'yo-its-a-secret',&lt;br&gt;     tokenExpireTime: '6h'&lt;br&gt;}&lt;/pre&gt;
&lt;h4 id="5390" class="graf graf--h4 graf-after--pre"&gt;db.js:&lt;/h4&gt;
&lt;pre id="aa46" class="graf graf--pre graf-after--h4"&gt;&lt;code class="markup--code markup--pre-code"&gt;const config = require('./config');&lt;br&gt;const Sequelize = require('sequelize');&lt;br&gt;var sequelize = new Sequelize(config.dbConnectionString);&lt;br&gt;require('sequelize-values')(sequelize);&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="b639" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;module.exports = sequelize;&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id="74a8" class="graf graf--h4 graf-after--pre"&gt;router.js:&lt;/h4&gt;
&lt;pre id="8e3d" class="graf graf--pre graf-after--h4"&gt;&lt;code class="markup--code markup--pre-code"&gt;module.exports.set = app =&amp;gt; {&lt;br&gt;     //endpoints will be here soon&lt;br&gt;}&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id="884a" class="graf graf--h4 graf-after--pre"&gt;index.js:&lt;/h4&gt;
&lt;pre id="2919" class="graf graf--pre graf-after--h4"&gt;&lt;code class="markup--code markup--pre-code"&gt;const express = require('express');&lt;br&gt;const http = require('http');&lt;br&gt;const bodyParser = require('body-parser');&lt;br&gt;const app = express();&lt;br&gt;const config = require('./config');&lt;br&gt;const router = require('./router');&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="948e" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;app.use(bodyParser.json());&lt;br&gt;app.use(bodyParser.urlencoded({&lt;br&gt;     extended: true&lt;br&gt;}));&lt;br&gt;app.use(express.static('client'));&lt;br&gt;router.set(app);&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="ca90" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;app.listen(config.port, () =&amp;gt; console.log('App listening on port '+ config.port));&lt;/code&gt;&lt;/pre&gt;
&lt;p id="cc6d" class="graf graf--p graf-after--pre"&gt;After you’ve finished creating the files in the main folder, you have to define data models. To do this, create a folder models with the file &lt;strong class="markup--strong markup--p-strong"&gt;index.js&lt;/strong&gt; inside. Like this:&lt;/p&gt;
&lt;h4 id="7126" class="graf graf--h4 graf-after--p"&gt;/models/index.js:&lt;/h4&gt;
&lt;pre id="77ef" class="graf graf--pre graf-after--h4"&gt;&lt;code class="markup--code markup--pre-code"&gt;const Sequelize = require('sequelize');&lt;br&gt;const sequelize = require('../db');&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="901a" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;const User = sequelize.define('user', {&lt;br&gt;    login: Sequelize.STRING,&lt;br&gt;    password: Sequelize.STRING,&lt;br&gt;});&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="ffdc" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;const Order = sequelize.define('order', {&lt;br&gt;     title: Sequelize.STRING,&lt;br&gt;     date: {&lt;br&gt;         type: Sequelize.DATE,&lt;br&gt;         defaultValue: Sequelize.NOW&lt;br&gt;      },&lt;br&gt;     user_id: {&lt;br&gt;         type: Sequelize.INTEGER,&lt;br&gt;         references: {&lt;br&gt;              model: User,&lt;br&gt;              key: 'id'&lt;br&gt;          }&lt;br&gt;      }&lt;br&gt; });&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="ccc6" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;User.hasMany(Order, {foreignKey: 'user_id'});&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="ff18" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;module.exports = {&lt;br&gt;     User,&lt;br&gt;     Order&lt;br&gt; }&lt;/code&gt;&lt;/pre&gt;
&lt;p id="9418" class="graf graf--p graf-after--pre"&gt;This is how you start your multilayer Node.js project. At this point we have an entry point into our application (&lt;strong class="markup--strong markup--p-strong"&gt;index.js&lt;/strong&gt;), two DB models (&lt;strong class="markup--strong markup--p-strong"&gt;models/index.js&lt;/strong&gt;) and some basic configuration.&lt;/p&gt;
&lt;h3 id="f4ce" class="graf graf--h3 graf-after--p"&gt;JWT Authentication&lt;/h3&gt;
&lt;p id="d70a" class="graf graf--p graf-after--h3"&gt;Before writing an actual API, let’s add authentication to our application. Create a services folder with files &lt;strong class="markup--strong markup--p-strong"&gt;user.js&lt;/strong&gt;and &lt;strong class="markup--strong markup--p-strong"&gt;auth.js&lt;/strong&gt; inside. Like this:&lt;/p&gt;
&lt;h4 id="4077" class="graf graf--h4 graf-after--p"&gt;/services/index.js&lt;/h4&gt;
&lt;pre id="ad81" class="graf graf--pre graf-after--h4"&gt;&lt;code class="markup--code markup--pre-code"&gt;const sequelize = require('../db');&lt;br&gt;const Users = require('../models').User;&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="c40b" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;const addUser = user =&amp;gt; Users.create(user);&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="0a6c" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;const getUserByLogin = login =&amp;gt; Users.findOne({where: {login}});&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="7817" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;module.exports = {&lt;br&gt;    addUser,&lt;br&gt;    getUserByLogin&lt;br&gt;}&lt;/code&gt;&lt;/pre&gt;
&lt;p id="e231" class="graf graf--p graf-after--pre"&gt;Once a user is logged-in, each subsequent request will include a token (JWT), allowing the user to access routes, services and resources according to the permissions stored in the token.&lt;/p&gt;
&lt;h4 id="329f" class="graf graf--h4 graf-after--p"&gt;/services/auth.js will handle JWT authentication:&lt;/h4&gt;
&lt;pre id="2b80" class="graf graf--pre graf-after--h4"&gt;&lt;code class="markup--code markup--pre-code"&gt;const bcrypt = require('bcrypt');&lt;br&gt;const jwt = require('jsonwebtoken');&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="83ff" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;const Users = require('../models').User;&lt;br&gt;const config =  require('../config');&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="339c" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;const authenticate = params =&amp;gt; {&lt;br&gt;      return Users.findOne({&lt;br&gt;          where: {&lt;br&gt;              login: params.login&lt;br&gt;          },&lt;br&gt;          raw: true&lt;br&gt;     }).then(user =&amp;gt; {&lt;br&gt;          if (!user)&lt;br&gt;              throw new Error('Authentication failed. User not found.');&lt;br&gt;          if (!bcrypt.compareSync(params.password || '', user.password))&lt;br&gt;              throw new Error('Authentication failed. Wrong password.');&lt;br&gt;          const payload = {&lt;br&gt;              login: user.login,&lt;br&gt;              id: user.id,&lt;br&gt;              time: new Date()&lt;br&gt;          };&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="973d" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;          var token = jwt.sign(payload, config.jwtSecret, {&lt;br&gt;              expiresIn: config.tokenExpireTime&lt;br&gt;          });&lt;br&gt;          return token;&lt;br&gt;      });&lt;br&gt;}&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="8d47" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;&lt;br&gt;module.exports = {&lt;br&gt;    authenticate&lt;br&gt;}&lt;/code&gt;&lt;/pre&gt;
&lt;p id="49b9" class="graf graf--p graf-after--pre"&gt;To handle requests for registration and authentication, our application should have a controller.&lt;/p&gt;
&lt;p id="9730" class="graf graf--p graf-after--p"&gt;Let’s create a file &lt;strong class="markup--strong markup--p-strong"&gt;auth.js&lt;/strong&gt; and place it in the controllers folder.&lt;/p&gt;
&lt;h4 id="e6a0" class="graf graf--h4 graf-after--p"&gt;/controllers/auth.js:&lt;/h4&gt;
&lt;pre id="30e2" class="graf graf--pre graf-after--h4"&gt;&lt;code class="markup--code markup--pre-code"&gt;const config =  require('../config');&lt;br&gt;const jwt = require('jsonwebtoken');&lt;br&gt;const bcrypt = require('bcrypt');&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="b145" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;const authService = require('../services/auth');&lt;br&gt;const userService = require('../services/user');&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="c2ae" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;function login(req, res){&lt;br&gt;     return authService.authenticate(req.body)&lt;br&gt;     .then(token =&amp;gt; {&lt;br&gt;          res.send({&lt;br&gt;               success: true,&lt;br&gt;               data: { token }&lt;br&gt;          });&lt;br&gt;     })&lt;br&gt;     .catch(err =&amp;gt; {&lt;br&gt;          res.send({&lt;br&gt;               success: false,&lt;br&gt;               message: err.message //not the best error handling.&lt;br&gt;               //for better error handling visit github repository, link provided below&lt;br&gt;          });&lt;br&gt;     })&lt;br&gt;};&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="f12b" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;function register(req, res){&lt;br&gt;     var login = req.body.login;&lt;br&gt;     return userService.getUserByLogin(req.body.login || '')&lt;br&gt;     .then(exists =&amp;gt; {&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="f9e1" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;          if (exists){&lt;br&gt;               return res.send({&lt;br&gt;                   success: false,&lt;br&gt;                   message: 'Registration failed. User with this email already registered.'&lt;br&gt;               });&lt;br&gt;          }&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="3f2b" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;          var user = {&lt;br&gt;               login: req.body.login,&lt;br&gt;               password: bcrypt.hashSync(req.body.password, config.saltRounds)&lt;br&gt;           }&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="8e22" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;          return userService.addUser(user)&lt;br&gt;          .then(() =&amp;gt; res.send({success: true}));&lt;br&gt;     });&lt;br&gt;};&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="dd54" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;module.exports = {&lt;br&gt;    login,&lt;br&gt;    register&lt;br&gt;}&lt;/code&gt;&lt;/pre&gt;
&lt;p id="9ebf" class="graf graf--p graf-after--pre"&gt;After this, we need to add endpoints to our API.&lt;/p&gt;
&lt;h4 id="5fcc" class="graf graf--h4 graf-after--p"&gt;You can do it in the router.js file:&lt;/h4&gt;
&lt;pre id="bcd1" class="graf graf--pre graf-after--h4"&gt;&lt;code class="markup--code markup--pre-code"&gt;const authController = require('./controllers/auth');&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="997f" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;module.exports.set = app =&amp;gt; {&lt;br&gt;    app.post('/login', authController.login);&lt;br&gt;    app.post('/register', authController.register);&lt;br&gt;}&lt;/code&gt;&lt;/pre&gt;
&lt;p id="40bd" class="graf graf--p graf-after--pre"&gt;Let’s start the server by running the command node &lt;strong class="markup--strong markup--p-strong"&gt;index.js &lt;/strong&gt;and test the login and register functionality.&lt;/p&gt;
&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--7ppNgcuv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/freeze/max/38/0%2A8XcQdWO2Gw4eqsFT.%3Fq%3D20" class="progressiveMedia-thumbnail js-progressiveMedia-thumbnail"&gt;&lt;img class="progressiveMedia-image js-progressiveMedia-image"&gt;&lt;img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://res.cloudinary.com/practicaldev/image/fetch/s--P4zDey6e--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1000/0%2A8XcQdWO2Gw4eqsFT."&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--NP8QDAPY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/freeze/max/38/0%2AMVTMd2V14lsPQ43D.%3Fq%3D20" class="progressiveMedia-thumbnail js-progressiveMedia-thumbnail"&gt;&lt;img class="progressiveMedia-image js-progressiveMedia-image"&gt;&lt;img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://res.cloudinary.com/practicaldev/image/fetch/s--CeLOCLKL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1000/0%2AMVTMd2V14lsPQ43D."&gt;&lt;h3 id="1605" class="graf graf--h3 graf-after--figure"&gt;Adding Layers&lt;/h3&gt;
&lt;p id="89d9" class="graf graf--p graf-after--h3"&gt;Now we have the Controller layer and the Data Access layer in our application. To link them together, we need the Service layer in between. Using layers is a good way to ensure separation of responsibilities, which allows making data, business logic and presentation code independent. The Presentational layer (user) interacts with the Controllers layer (API) that uses the Service layer (business rules) to access and modify data via the Data Access layer.&lt;/p&gt;
&lt;p id="21ee" class="graf graf--p graf-after--p"&gt;So, let’s start with our first service for the order model.&lt;/p&gt;
&lt;h4 id="1c9d" class="graf graf--h4 graf-after--p"&gt;Create a file services/order.js&lt;/h4&gt;
&lt;pre id="7b31" class="graf graf--pre graf-after--h4"&gt;&lt;code class="markup--code markup--pre-code"&gt;const Orders = require('../models').Order;&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="afe8" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;const getAll = () =&amp;gt; Orders.findAll();&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="fbbe" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;const getById = id =&amp;gt; Orders.findById(id);&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="dca6" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;const add = order =&amp;gt; Orders.create(order);&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="f5be" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;module.exports = {add, getAll, getById};&lt;/code&gt;&lt;/pre&gt;
&lt;p id="8098" class="graf graf--p graf-after--pre"&gt;Now, we can create a controller to work with that service.&lt;/p&gt;
&lt;h4 id="6d13" class="graf graf--h4 graf-after--p"&gt;controllers/order.js&lt;/h4&gt;
&lt;pre id="9208" class="graf graf--pre graf-after--h4"&gt;&lt;code class="markup--code markup--pre-code"&gt;const orderService = require('../services/order');&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="827b" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;function getOrders(req, res){&lt;br&gt;    orderService.getAll()&lt;br&gt;    .then(data =&amp;gt; res.send(data));&lt;br&gt;};&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="0351" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;function getOrder(req, res){&lt;br&gt;    orderService.getById(req.params.id)&lt;br&gt;    .then(data =&amp;gt; res.send(data));&lt;br&gt;}&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="804e" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;function addOrder(req, res){&lt;br&gt;    orderService.add({&lt;br&gt;        title: req.body.title,&lt;br&gt;        user_id: 1&lt;br&gt;    })&lt;br&gt;    .then(data =&amp;gt; res.send(data));&lt;br&gt;};&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="22f6" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;module.exports = {&lt;br&gt;    getOrders,&lt;br&gt;    getOrder,&lt;br&gt;    addOrder&lt;br&gt;}&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id="f14b" class="graf graf--h4 graf-after--pre"&gt;And one more thing we need to finish our orders part of RESTful API is to add endpoints to router.js:&lt;/h4&gt;
&lt;pre id="40cd" class="graf graf--pre graf-after--h4"&gt;&lt;code class="markup--code markup--pre-code"&gt;const orderController = require('./controllers/order');&lt;br&gt;…&lt;br&gt;   app.get('/orders', orderController.getOrders);&lt;br&gt;   app.get('/orders/:id', orderController.getOrder);&lt;br&gt;   app.post('/orders', orderController.addOrder);&lt;/code&gt;&lt;/pre&gt;
&lt;p id="d768" class="graf graf--p graf-after--pre"&gt;Here’s some testing illustration of a working API:&lt;/p&gt;
&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--xvN5zvmb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/freeze/max/38/0%2AUX2SARvacaowtBZJ.%3Fq%3D20" class="progressiveMedia-thumbnail js-progressiveMedia-thumbnail"&gt;&lt;img class="progressiveMedia-image js-progressiveMedia-image"&gt;&lt;img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://res.cloudinary.com/practicaldev/image/fetch/s--Af-otSyY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1000/0%2AUX2SARvacaowtBZJ."&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Cy9O05_5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/freeze/max/38/0%2A57jT_t78_id0iF1e.%3Fq%3D20" class="progressiveMedia-thumbnail js-progressiveMedia-thumbnail"&gt;&lt;img class="progressiveMedia-image js-progressiveMedia-image"&gt;&lt;img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://res.cloudinary.com/practicaldev/image/fetch/s--5gUEOlJL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1000/0%2A57jT_t78_id0iF1e."&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2yDFFqrp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/freeze/max/38/0%2At59vn7ZhHzPWTvCg.%3Fq%3D20" class="progressiveMedia-thumbnail js-progressiveMedia-thumbnail"&gt;&lt;img class="progressiveMedia-image js-progressiveMedia-image"&gt;&lt;img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://res.cloudinary.com/practicaldev/image/fetch/s--BppCOosY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1000/0%2At59vn7ZhHzPWTvCg."&gt;&lt;p id="d5c4" class="graf graf--p graf-after--figure"&gt;The next thing we need is to allow access only to authenticated users. To do this, let’s add middleware that checks if the user is logged in:&lt;/p&gt;
&lt;h4 id="849e" class="graf graf--h4 graf-after--p"&gt;middlewares/auth.js:&lt;/h4&gt;
&lt;pre id="9ea4" class="graf graf--pre graf-after--h4"&gt;&lt;code class="markup--code markup--pre-code"&gt;const jwt = require('jsonwebtoken');&lt;br&gt;const config =  require('../config');&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="3cfc" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;const checkAuth = (req, res, next) =&amp;gt; {&lt;br&gt;    var token = req.headers['token'];&lt;br&gt;    if (!token)&lt;br&gt;        return res.status(403).send({ auth: false, message: 'No token provided.' });&lt;br&gt;    &lt;br&gt;    jwt.verify(token, config.jwtSecret, (err, decoded) =&amp;gt; {&lt;br&gt;        if (err)&lt;br&gt;            return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="4c4f" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;    req.user = {&lt;br&gt;         login: decoded.login,&lt;br&gt;         id: decoded.id&lt;br&gt;    };&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="b8ce" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;    next();&lt;br&gt;    });&lt;br&gt;}&lt;/code&gt;&lt;/pre&gt;
&lt;pre id="d6f2" class="graf graf--pre graf-after--pre"&gt;&lt;code class="markup--code markup--pre-code"&gt;module.exports = {&lt;br&gt;    checkAuth&lt;br&gt;}&lt;/code&gt;&lt;/pre&gt;
&lt;p id="bcf4" class="graf graf--p graf-after--pre"&gt;After this, the authentication middleware should be used as the middleware argument (the second one) in endpoints functions. Now, the user can’t access data without providing a valid authentication token.&lt;/p&gt;
&lt;pre id="27bb" class="graf graf--pre graf-after--p"&gt;&lt;code class="markup--code markup--pre-code"&gt;app.get('/orders', authMiddleware.checkAuth, orderController.getOrders);&lt;br&gt;app.get('/orders/:id', authMiddleware.checkAuth, orderController.getOrder);&lt;br&gt;app.post('/orders', authMiddleware.checkAuth, orderController.addOrder);&lt;br&gt;app.get('/user_orders', authMiddleware.checkAuth, userController.getUsersWithOrders)&lt;/code&gt;&lt;/pre&gt;
&lt;p id="29c6" class="graf graf--p graf-after--pre"&gt;As you can see it works :)&lt;/p&gt;
&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--7ZzYnMoT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/freeze/max/38/0%2AliSSB6AatlJftxbi.%3Fq%3D20" class="progressiveMedia-thumbnail js-progressiveMedia-thumbnail"&gt;&lt;img class="progressiveMedia-image js-progressiveMedia-image"&gt;&lt;img class="progressiveMedia-noscript js-progressiveMedia-inner" src="https://res.cloudinary.com/practicaldev/image/fetch/s--p9JyZUa4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1000/0%2AliSSB6AatlJftxbi."&gt;&lt;h4 id="ef98" class="graf graf--h4 graf-after--figure"&gt;The final thing we need to do is define the addOrder function.&lt;/h4&gt;
&lt;pre id="a9ae" class="graf graf--pre graf-after--h4"&gt;&lt;code class="markup--code markup--pre-code"&gt;function addOrder(req, res){&lt;br&gt;    orderService.add({&lt;br&gt;         title: req.body.title,&lt;br&gt;         user_id: req.user.id&lt;br&gt;    })&lt;br&gt;    .then(data =&amp;gt; res.send(data));&lt;br&gt;};&lt;/code&gt;&lt;/pre&gt;
&lt;p id="a8c8" class="graf graf--p graf-after--pre"&gt;And that’s it! We’ve created a small app with RESTful API. According to the Multilayer Architecture concept, we have the Controllers layer, the Service layer and the Data Access layer. Our API with JWT authorization makes it easy to add the Presentational layer, e.g. web application or mobile application.&lt;/p&gt;
&lt;p id="6d2e" class="graf graf--p graf-after--p graf--trailing"&gt;Feel free to check the code in the &lt;a href="https://github.com/VitaliiKulyk/asap" class="markup--anchor markup--p-anchor" rel="nofollow noopener"&gt;&lt;strong class="markup--strong markup--p-strong"&gt;repository&lt;/strong&gt;&lt;/a&gt;. Well, don’t just stand there — go ahead and try it yourself. Good luck from &lt;a href="https://www.eliftech.com/" class="markup--anchor markup--p-anchor" rel="nofollow noopener"&gt;&lt;strong class="markup--strong markup--p-strong"&gt;ElifTech&lt;/strong&gt;&lt;/a&gt;!&lt;/p&gt;


</description>
      <category>node</category>
      <category>restfulapi</category>
      <category>jwt</category>
      <category>postgres</category>
    </item>
  </channel>
</rss>
