NodeJS and CQRS Based REST APIs Using ExpressJS SubApps

Before going on this post, i highly recommend to read first my last post about CQRS , this will give you how i am thinking about CQRS and the added value to build CQRS based REST APIs.

Implementation Steps

  1. Create Authorization Module
  2. Building two SubApps (1st for Commands and other for Queries)
  3. Handle the logging and Authorization
  4. Create App (Entry point) to consume the SubApps

If you are new in NodeJS sub apps – its is an ExpressJS way to extract part of your API functionality in separate JS Node and consume (use) it when ever you need.

lets start with the code …

1. Create Authorization Module

//  ./authorization-handler.js
function functionAuth(req,res,next)
{
     var auth = true; // Write Down Your Auth Logic Here
     if(!auth)
     {
          console.log('Non Authorized To Function.');
          res.status(403).send('Not Authorized');
     }
     else
          console.log('Authorized.');
}

function modelAuth(req,res)
{
     var auth = true; // Write Down Your Auth Logic Here
     if(!auth)
     {
          console.log('Non Authorized To Model.');
          throw ('Invalid Token');
     }
     else
          console.log('Authorized.');
     }

exports.modelAuth = modelAuth;
exports.functionAuth = functionAuth;

2. Building Sub App for Commands

//  ./commands.js (POST, PUT, DELETE)
const express= require('express');
const authhandler = require('./authorization-handler');
var app = new express();

app.on('mount', function (parent) {
  console.log('Commands API Mounted');
});

app.all('*',function(req,res,next){
  try{
    authhandler.modelAuth();
    next();
  }
  catch(ex)
  {
    res.status(403).send(ex)
  }
})
app.post('/get',authhandler.functionAuth,function(req,res,next)
{
  res.send('get command executed');
})

module.exports = app;

3. Building Sub App for Queries

//  ./queries.js
//Do the same as the commands for GET functions

4. Building the Entry Point

//  ./app.js
const express = require('express');
const authhandler = require('./authorization-handler');
const commands = require('./commands');
const queries = require('./queries');
var app = new express();

app.use('/commands',commands);
app.use('/queries',queries);

app.listen(7777,function(req,res){
  console.log('7777 Server Is Working ...');
});

And we have done 🙂

Advertisements

One thought on “NodeJS and CQRS Based REST APIs Using ExpressJS SubApps

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s