Introducing CQRS (Command Query Responsibility Segregation)

Dears,

If you are a Domain Driven or Micro-services based developer, you might be interested to build your coming API(s) in CQRS models instead of the current traditional CRUD approach.

First, based on Martin Fowler article about CQRS, Greg Young is the founder of this pattern, but honestly is don’t believe CQRS is a pattern at all, it is more simpler than that, the pattern is something solving a specific problem, but CQRS is not a solution for anything, it is a way to separate and elevate your code to be more expandable and easy to handle specially with complex domains.

What is CQRS

Its easy to figure out the target from the name (Command Query Responsibility Segregation) where you separate between the API Commands and Queries.

  • Commands (Changes the state of the object) [Post, Put, Delete] (e.g. Writes or Update on the DataSource)
  • Query (Never Changes the state of the object) [Get] (e.g. Selecting from DataSource)

and the first thing comes to your mind, yes its really important for code security !

I remember a project written in NodeJS where i elevated the CQRS models to be with different security token check.

1. Simply How It works ?

Define your domain (keep the business in mind)

Domain is always maps to business value, an independent and totally agnostic in terms of behavior, and we might talk about this later in separate post, but first remember that business separation is all you should care about.

Create two models (Command & Query)

Its kind of extra domain separation but not a sub-domain, as Commands and Queries give the domain its full behavior.

CQRS and Token Authorization

I am talking about API authorization where you just allow authorized requests to access specific API, and this could be on the Model Route or on the Function Route.

NodeJS (Model Level Authorization)

const express= require('express');
const authorizationHandler = require('/authorization-handler');
var app = new express();

app.all('*',function(req,res,next){
  try{
   authorizationHandler.authorizeModel();
   next();
  }
  catch(ex)
  {
    res.status(403).send(ex);
  }
});

app.get("/get/:id",function(req,res){
 res.send(/*What Ever ...*/);
});

app.post("/post",function(req,res){
 res.send(/*What Ever ...*/);
});

C# (Model Level Authorization)

[RoutePrefix("api/employee/{token}")]
[Authorize]
public class EmployeeController : ApiController
{
    [Route("get/{id}")]
    public async Task Get(int id, string token)
    {
          return Ok(/*What Ever*/);
    }
    [Route("post")]
    public async Task Post([FromBody] Employee employee, string token)
    {
          return Ok(/*What Ever*/);
    }
}

NodeJS (Function Level Authorization)

const express= require('express');
var app = new express();

app.all('*',function(req,res,next){
 /*No Authorization here ...*/
 next();
});

app.get("/get/:id",authorizationHandler.authorizeFunction,function(req,res,next){
 res.send(/*What Ever ...*/);
});

app.post("/post",authorizationHandler.authorizeFunction,function(req,res,next){
 res.send(/*What Ever ...*/);
});

C# (Function Level Authorization)

[RoutePrefix("api/employee/{token}")]
public class EmployeeController : ApiController
{
    [Route("get/{id}")]
    [Authorize]
    public async Task Get(int id, string token)
    {
          return Ok(/*What Ever*/);
    }
    [Route("post")]
    [Authorize]
    public async Task Post([FromBody] Employee employee, string token)
    {
          return Ok(/*What Ever*/);
    }
}

In CQRS, it will be a little different where you have to authorize on the Model Level to make sure the request accessing the Commands model is authorized to change the object state, and the authorization is less sensitive here. For this case in specific you can use my implementation for a simple NodeJS two levels authorization, where the primary Authorization will be on the model level (Mandatory) and second will be on the function level (Optional).

CQRS and Event Sourcing working together

If you are not following, Event Sourcing is a design approach to publish events instead of executing DataSource operations and a publisher will execute these events in order (if dependent) to the data source.

I wish you started to figure out how CQRS is very useful for Event Sourcing !

We will talk about this in future post in details because it deserves.

Thanks for now, try it by your self and make it a life style 😉

Regards,

Sameh Selem

Advertisements

One thought on “Introducing CQRS (Command Query Responsibility Segregation)

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s