Building a MicroService APIs using the GateWay Pattern

Intro.

I will assume that you know the theory of MicroServices, and i will assume that you need a hands on reference aid on how to build a Complete MicroService Based REST APIs utilizing the benefits of the concept and also simple enough to build over.

Values we seek from MicroService 

  1. Build as much independent raw functioning services fulfilling the whole domain functionality.

  2. Making sure that every Service is running and maintained separately without any crack due to another service defect.

  3. Providing a separate deployment ready services, the thing that will aid on managing the load upon certain service separately with MAX. cost control.

  4. Supporting any combination of workflows using the MicroServices without the need to change the Services implementations.

I use a GateWay for MicroServices communication

The alternative is “Point to Point” communication, where the services can communicate with each other for sake of certain workflow or dependencies, but the issue about this technique is that we are no fully satisfying the Services dependencies and highly coupling the services stability on each others, and further more the Point to Point configuration is a nightmare specially when we have many domains.

The Design Essentials

  1. Every MicroService represents a different domain with standalone and self concerned business logic.

  2. Every MicroService doesn’t has aware enough with the other MicroServices end points of even functionality, so MicroServices direct communication is totally prohibited.

  3. Every MicroService is a REST API with unique EndPoint and could be hosted separately with unique security configurations.

  4. GateWay is a REST API with unique EndPoint.

  5. GateWay is the only EndPoint exposed to the FrontEnd Applications, so Microservices are only accessible by the GateWay.

  6. GateWay is the the place to build specific business workflow using the different MicroServices.

  7. Finally, and i haven’t seen any one apply this role 100%, is to make sure that every MicroService using its own DataBase and DataModels with any need to data from other Services DataBases, this is perfect to keep improving you Design to fulfill this concept and to save the separation down to all layers.

Sample Generic Business Practice

We need to build a Microservices to handle a TimeSheet System functionality.

we will need the following MicroService:

  1. UserAPI (Host In http://ip:port/api)
    1. PostNewUser        http://ip:port/api/post
    2. PutExistUser         http://ip:port/api/put/id
    3. DeleteExistUser   http://ip:port/api/delete/id
    4. GetAllUsers           http://ip:port/api/get
    5. GetUserById          http://ip:port/api/get/id
  2. MessagingAPI (Host In http://ip:port/api)
    1. GetAllMessages
    2. PostMessage
    3. DeleteMessage
    4. PostReply
  3. VacationAPI
    1. PostNewVacation
    2. DeleteNewVacation
    3. GetAllVacations
    4. PutExistVacation
  4. TimesheetAPI
    1. PostNewTimeSheet
    2. PutExistTimeSheet
    3. GetAllTimeSheets
  5. ReportingAPI
    1. GetReportDataById
  6. ProjectAPI
    1. PostNewProject
    2. PutExistProject
    3. DeleteProject
    4. GetAllProjects
    5. GetProjectById
    6. AddUserToProject

Now, we have 6 Separate and independent MicroServices hosted separately in different endpoints (ip/port).

Now we need to build another REST API represents the GateWay handelling the business Workflows to call from the FrontEnd Application (DeskTop APP., Web. APP. , Mobile, another Service , …etc).

 

e.g. Build GateWay REST function to Create Project and Add all users to it.

Steps In GateWay :

  1. Create Project by calling the ProjectAPI function PostNewProject

  2. Get All User by calling the  UserAPI function GetAllUsers

  3. Enumerate on the Users and Call The ProjectAPI function AddUserToProject.

  4. Return Operation Status

This Function should be a Post function expects [From Request Body] an object of Project, and the GateWay function should respond with Status (200, 404, 400, 500, …etc) according to how you handle the API errors.

so at the end , the FrontEnd application communicates with an API like http://gatewayip:port/api/postprojecttoeveryone

Important Notes

  1. The Microservices changes cadence should be minimal as it provides a row fundamental CRUD operations over specifuc business model.

  2. Every business Application with different requirements require New GateWay and not new MicroServices.

  3. Exception Handling and Error Pulling should be in a way to stop the technical inner exception on the layer of GateWay and Log It, and send Friendly helpful messages with Error Code as a GateWay responce.

Advertisements

Using AngularJS $apply to call functions across different controllers within same module

Intro.

If you read my old post about Splitting Application Page into Separate AngularJS MINI Components , you might need to also read this post as i am talking here about a way to call a controller function from different $scope using the $apply module (Digest Loading).

Why we might need this?

This is important when we are inside a $scope of controller of a directive or what ever and we need to call or execute another controller $scope function to get or post or what ever the function does.

Indeed you can use the AngularJS $rootscope but all am doing here is introducing another solution.

How to do it ?

Lets assume that we have two different Controllers assigned to two different Directives and two different modules, and from the first Controller ($scope) we need to call function inside second Controller ($scope).

In real case, this could be a “Menu Controller Btn.” toggles “Body Controller Div” Visibility  or what ever you might need.

This is a way to access another $scope functionality without changing the $scope.

First, assuming that the external $scope that we need to call a function inside is assigned to HTML Div or whatever with Class or Id, we need this to get the element assigned $scope by element ID or Class Name.

Note that all the following code snippets should be inside the first controller not the one the function implemented inside.

var externalScope = angular.element($("#comp-body")).scope();

I assumed here that we have an HTML Element with Id = comp-body and this element Controller is the one we seek its functions.

Then lets call the function inside this scope as if we are inside it

externalScope.$apply(function () {
 externalScope.doSomething();
});

Note that, doSomething should be in externalScope ($scope) or implemented this way:

$scope.doSomething = function()
{
//What ever ...
};

Important Note

In some cases you might need to add the last code snippet inside

$timeout(function () {
//put the $apply code here ...
});

to make sure you are not conflicting with same $scope in progress process.

 

Thanks,

Splitting Application Page into Separate AngularJS MINI Components

Intro.

In glance, and over decades of building many Web Applications, i can say that we are the lucky generation who has the opportunity to witness the “Rapid Evolution” of the front end development. And am not here to utilize this post for talking about the historical road map or even to judge any of these many sprints, am only giving a modern “Technologically Oriented” technique to build a (Smarter, Easier to Maintain, Better for re usability) and Firm Web Application page using AngularJS 1.x.

Case Study

I need to build an application page(s) with several parts and to provide a smart stable way to communicate between these parts and indeed to reuse them in other pages.

Assumption

I will assume that you have enough experience with AngularJS and good understanding to the basic AngularJS Definitions like (Module, Directive, Service, Controller and Template). and Upon this assumption i just guide you to use these framework in way to provide the Titled “Split Your Application Page Into MINI Components”.

Step 1: Conceptually Split Your Page to as MINI Components as you can.

I remember that I’ve worked in application and i created a component for a “Button” and i handled the Hover, Click, In Progress behavior all inside this Directive.

This Step is very important but don’t spend a lot in as it is kind of recursive phase to keep updating and split more or merge according to how work goes.

I will give you a hint of some elementary concepts to take care while splitting the page into Components:

  1. Define the Globally Shared Parts (e.g. Header, Footer, Menu, …etc).
  2. Define the Partially Shared Parts (e.g. Profile Picture in account management Pages)
  3. Define or Draw the different page parts Dependency and Communication (In/Out) (e.g. A Btn. on the header can Toggle Page body contents visibility, or like Filter changes should update results).
  4. Avoid Over Splitting that will add useless effort to integrate and inject.

and overall, stop we you feel you are about to loose the Orchestration between all page parts.

Step 2: Build The Solution Structure 

There are several opinions regarding this part and different schools, and i can’t tell you whats better but you have to always know that whatever concept you will implement, you will sacrifice the strength of the other one. I will show here two different ways and indeed you can scout over another.

The Functional Structure people here separate the components by function, it means every component with separate functionality be in a separate folder contains all of its artifacts (e.g. JS, HTML, LESS or CSS), and also the sub components.

pic-1

Pic 1 : The Functional Structure

The File Type Structure This one is not business or functional oriented as mush as it is a development structure, where you are grouping the same File Type artifacts in the same Folder, and you use the file name to refer to the function related to.

pic-2

Pic 2:The File Type Structure

You are the best to define the need to pick any or merge between them to define your own structure, but you always should consider some elements to decide based upon, like

  1. How you will bundle the application , as the File Type is mush easier that the Functional one in terms of bundling .
  2. Minification Scripts.
  3. Template Mapping and Template Path Security configurations.

Step 3: Build the Globally Shared Components First then Page Specific Components.

Because 99% of the Globally Shared components are the most simple components and the less dependent on other parts, so you better start with to build and define your framework first and firmly continue injecting further components.

Sample Component Implementation (Building Header Component)

Define the Component module to use later in Parent Module injection.

angular.module('comp-header', [])

Assign the Component Directive pointing to the Component Template.

angular.module('comp-header', []).directive('compHeader', function () {
return {
        templateUrl: 'components/header/template.html' 
       };
});

Create the directive Controller

angular.module('fcomp-header').controller('CompHeader',
['$scope', '$element', '$timeout',
function ($scope, $element, $timeout,) {

angular.element(document).ready(function () {
    //Write Down The Directive Start Up Logic Here
});
}]);

Build The Component Template (HTML) and assign the created Controller to

< div class="comp-header" ng-controller="CompHeader">
Write Down Your HTML here ...
< /div>

Inject the Created component to the Page Module

angular.module('home-page', ['ngRoute', 'ui.bootstrap', 'ngAnimate', 'comp-header']);
angular.module('home-page');

Finally : Use the components in the home page

< div id="CompHeader">< /div>

Now, You should be able to move on with the rest of your components and keep injecting in the Page of interest.

Further to read in same context:
1. Using Angular $apply to call functions across different controllers within same module.
2. Using Angular $sceDelegateProvider to add the Directive Template URL to the Module White List.