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

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

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.

Alternatives to build todays Web Applications and different hosting choices

Dears,
While we are so confused with What to follow for the optimal Architecture and what tool to use and what is the best integration to build a stable and responsive WEB application. and also where to host for stable accessibility. i have defined three alternatives for building a Web APP. with optimal hosting for each.

Note that you can comment with more alternatives and i promise i will update the post directly.

Alternative 1: For Mission Critical Apps

DataBase : SQL Server or ORACLE

Server Side APIs :

  1. Entity Framework  : For Database object representation and Database Operation management
  2. ASP.net WEB APIs : For Fast and Simple REST APIs.
  3. WCF Services : for Dual Binding and Custom Security.

Data Binding and Manipulations :

  1. AngularJS 1.x : If your UI is Template Oriented and no UI Dynamic creation expected.
  2. ReactJS : If you you seek a Script First Data Driven APP, and if your UI is highly Dynamic upon the Data with different Conditions.
  3. ReactJS : If you want to create a WorkFlow.
  4. D3JS : For Fancy SVG Charts, Comparisons, Interactive and Organized and Dynamic Data Representations.
  5. ThreeJS : If you want to add 3D or Animation.

Front End Business logic :

  1. JavaScript : If you and your team have no problems with Heavy Scripting and not fully customized Object Oriented code.
  2. ECMAScript : If you are like the above but need to write less code and more structured and readable, and want to keep the Un-Typed Scripting features (variables are not typed, all vars).
  3. Type Script : for sake of minimal code, as much like C# and Java, Fully Object Oriented with interfaces, for building modules with access modifiers (public, private , ..etc), and for Type and Build  Error Check in Compile Time.
  4. CoffeScript : Just like the ECMA but wants to witie RUBY or PYTHON like Code with space separation for code block.

Host : Windows Server

Alternative 2: For Non-Mission Critical and Huge Data Manipulation

DataBase : MongoDB, Cassandra (I recommend Mongo)

Server Side APIs :

  1. NodeJS : For Database object representation and Database Operation management.
  2. ASP.net WEB APIs : REST APIs
  3. WCF  Services : for Dual Binding and Custom Security.

Data Binding and Manipulations :

  1. AngularJS 1.x : If your UI is Template Oriented and no UI Dynamic creation expected.
  2. ReactJS : If you you seek a Script First Data Driven APP, and if your UI is highly Dynamic upon the Data with different Conditions.
  3. ReactJS : If you want to create a WorkFlow.
  4. D3JS : For Fancy SVG Charts, Comparisons, Interactive and Organized and Dynamic Data Representations.
  5. ThreeJS : If you want to add 3D or Animation.

Front End business logic :

  1. JavaScript : If you and your team have no problems with Heavy Scripting and not fully customized Object Oriented code.
  2. ECMAScript : If you are like the above but need to write less code and more structured and readable, and want to keep the Un-Typed Scripting features (variables are not typed, all vars).
  3. Type Script : for sake of minimal code, as much like C# and Java, Fully Object Oriented with interfaces, for building modules with access modifiers (public, private , ..etc), and for Type and Build  Error Check in Compile Time.
  4. CoffeScript : Just like the ECMA but wants to witie RUBY or PYTHON like Code with space separation for code block.

Host :

  1. DataBase Server : Windows Server or Linux (I recommend)
  2. Application Server : IIS over Windows in case of WCF or WEB APIs , Linux for the NodeJS.

Alternative 3: For Cloud Ready Application

DataBase :

  1. Create a Cloud VM [Windows or Linux – Linux is better for low prices](From AZURE or Google Compute pr AMAZON) and install mongoDB.  (NB. MongoDB required High Memory Machine so focus on the RAM).
  2. Use AZURe mongoDB service or Google Mongo Service, that is more scaleable and will take you out of the headache of Database Server management and Configuration, but much more costly compared with the last option.
  3. Store Your Data Over Cloud Provider Storage Service (I recommend AZURE Table Storage for Tabular Data and AZURE Blob Storage for File Storage) NB. Revise this post before using The Table Storage.

Server Side APIs :

  1. NodeJS : For Database object representation and Database Operation management.
  2. ASP.net WEB APIs : REST APIs
  3. WCF  Services : for Dual Binding and Custom Security.

Data Binding and Manipulations :

  1. AngularJS 1.x : If your UI is Template Oriented and no UI Dynamic creation expected.
  2. ReactJS : If you you seek a Script First Data Driven APP, and if your UI is highly Dynamic upon the Data with different Conditions.
  3. ReactJS : If you want to create a WorkFlow.
  4. D3JS : For Fancy SVG Charts, Comparisons, Interactive and Organized and Dynamic Data Representations.
  5. ThreeJS : If you want to add 3D or Animation.

Front End business logic :

  1. JavaScript : If you and your team have no problems with Heavy Scripting and not fully customized Object Oriented code.
  2. ECMAScript : If you are like the above but need to write less code and more structured and readable, and want to keep the Un-Typed Scripting features (variables are not typed, all vars).
  3. Type Script : for sake of minimal code, as much like C# and Java, Fully Object Oriented with interfaces, for building modules with access modifiers (public, private , ..etc), and for Type and Build  Error Check in Compile Time.
  4. CoffeScript : Just like the ECMA but wants to witie RUBY or PYTHON like Code with space separation for code block.

Host :

  1. DataBase Server : as illustrated in the DataBase part
  2. Application Server :

If you use WEB APIs or WCF : Use AZURE APP Service for easier and faster updates or indeed Windows VM.

If you use NodeJS you can host in Linux VM or Windows VM.

General Notes From My Experience:

  1. NodeJS is implemented over Chrome V8 Engine (compiler), so it supposed to be faster that the WEB APIs and indeed the WCF.
  2. WCF Service is best choice when it comes to Dual HTTP Binding with Custom Security Configurations.
  3. AZURE Cloud is easier than Google compute when it comes to Scaling Up/Down.
  4. Google Compute Engine is much more Lower in price than AZURE even for Windows Machines.
  5. Google Compute Engine team might suspend your VM for days if they felt that you are misaligned with the Terms Of Use , and they might re open when they discover that they were wrong !!
  6.  Angular2 will introduce the Dynamic Component like the ReactJS with much more better performance than Angular 1.x.

Useful Links Regarding the Above:

Click For more Info about how to install and Configure MongoDB in Windows.

Click For more Info about how to install and Configure MongoDB in Linux.

Click For more Info about how to create a REST API using node JS over MongoDB.

Click For Getting Started with ASP.net WEB APIs

Click For Angular Official website

Click for ReactJS Official website

Click for D3Js Official website

Click for ECMAScript Official website

Click for TypeScript Official website

Click for ThreeJS Official website

Step X Step : Start with NodeJS to create REST API with CRUD operations over MongoDB

Dears,

As one of the long list of Posts targeting the  Mean Stack, as i’ve already published a couple of posts targeting MongoDB for MS Windows Users and Linux Users , we will illustrate in this post how to build a REST API using NodeJS over MongoDB and a simple Client to Use the API.

Assumption

I will assume that you already know  what is NodeJS and also will assume that you installed MongoDB in your Local Machine (for detailed step x step reference , get back to my post here).

Note that its all JavaScript and nothing more, so you must be scripting lover to stand until the end of the post.

Step 1 : Installing the NodeJS Prerequisites

NodeJS is a Server Side Artifact, it means it is not Client Exposed JavaScript, so you have to know that while we moving through the Post steps, its not the real case to have the NodeJS and the Client project in the same device.

Now, lets start.

1 – Create a Folder anywhere in your machine, for my demo will be on the Desktop, Name it Node Scripts.

2 – Open Node.js command prompt and navigate to the created folder

cd C:\Users\sselim\Desktop\Node Scripts

3 – Install the Express Module in your Project

npm install express

Note that Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications and as we are going to use NodeJS to expose Crud Functions as a REST HTTP APIs, so we have to install it.

3 – Install the MongoDB Module in your Project

npm install mongodb

This is Mandatory indeed to let the NodeJS Express Compiler to understand the MongoDB Scripting we are going to build in farther step.

4 – Install the Body Parser Module in your Project

npm install body-parser

Like any CRUD Operations (GET, POST, PUT, DELETE), to let the Post Method to read from the request body and parse the contents and start using, you have to install the body-parser module first.

5 – Install the Multer Module in your Project

npm install multer

Multer is a NodeJS middleware for handling multipart/form-data

by reaching this step you installed all the prerequisites required for compiling and running your code and you have to find a folder with name node_modules created inside your project root folder (Node Scripts in my case) and inside this folder you will find 4 folders created (one for each module installed).

Step 2: Scripting the REST API

we are going to build a REST Function using NodeJS Syntax and compile using the Express and access using simple HTTP request.

I will work on a Film model with three Props. (Name, Language, Category), so we will start building the Controller JS that holds the CRUD methods for this Model.

1 – Inside the last created folder (Node Scripts) create a JS file and name it Film.js.

2 – In the created blank JS file we will start including the installed modules references

var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var MongoClient = require('mongodb').MongoClient, format = require('util').format;

var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }));

3 – Add a line for MongoDB Connection String

var ConnectionString = 'mongodb://127.0.0.1:27017/';

4 – Create the Server object to listen to requests to the Port of interest (i will use 8080 for my Demo)

var server = app.listen(8080, function () {
    console.log("FILMS API running at http://127.0.0.1:8080");
});

Note that as i mentioned before, the IP is 127.0.0.1 (localhost) and you should replace with the production IP when it comes to real work.

Step 3: CRUDing

We will create four function for covering the (Get All, Get By Key, Insert, Delete and Update) over the Film model.

1 – GetAll (Get Function read no parameters or even from the body)

app.get('/GetAll', function (req, res) {
    MongoClient.connect(ConnectionString + 'mongonodetest', function (err, db) {
        if (err) throw err;
        var collection = db.collection('Films')
                           .find({})
                           .toArray(function (err, docs) {
                               if (docs)
                                   res.json(docs);
                               else
                                   res.json(new Array());
                           });
    });
});

2 – GetByKey (Get Function Reads the Film Name parameter ‘Key’ from the request URL Parameters )

app.get('/GetByKey/:key', function (req, res) {
    MongoClient.connect(ConnectionString + 'mongonodetest', function (err, db) {
        if (err) throw err;
        var collection = db.collection('Films')
                           .find({ "Name": req.params.key })
                           .toArray(function (err, docs) {
                               if (docs)
                                   res.json(docs);
                               else
                                   res.json(new Array());
                           });
    });
});

3 – UpdateByKey (Post Function Reads the Film Name parameter ‘Key’ from the request URL Parameters and parse the new Film object from the the quest body)

app.put('/UpdateByKey/:key', function (req, res) {
    MongoClient.connect(ConnectionString + 'mongonodetest', function (err, db) {
        if (err) throw err;
        var collection = db.collection('Films')
                           .replaceOne({ "Name": req.params.key }, req.body
                           , function (err, docs) {
                               if (docs)
                                   res.json(docs);
                               else
                                   res.json(new Array());
                           });
    });
});

4 – InsertByKey (Post Function  parse the Film object from the the quest body)

app.post('/Insert', function (req, res) {
    MongoClient.connect(ConnectionString + 'mongonodetest', function (err, db) {
        if (err) throw err;
        var collection = db.collection('Films')
                           .insertMany(req.body
                           , function (err, docs) {
                               res.json('Done');
                           });
    });
});

5 – DeleteByKey (Get Function Reads the Film Name parameter ‘Key’ from the request URL)

app.get('/DeleteByKey/:key', function (req, res) {
    MongoClient.connect(ConnectionString + 'mongonodetest', function (err, db) {
        if (err) throw err;
        var collection = db.collection('Films')
                           .deleteMany({ "Name": req.params.key },
                            function (err, docs) {
                                res.json('Done');
                            });
    });
});

Now your REST API is ready, one last step is to run the API to be available for HTTP requests, or to make the server object we created above specific socket (IP:Port) to start listening to requests.

Do this by writing the command inside the Node.js command prompt

node Films.js

a line display the following should come up

FILMS API running at http://127.0.0.1:8080

Step 4 : Creating the Client

Now, lets build a very simple AJAX calls to request the NodeJS APIS at the Predefined Socket (127.0.0.1:8080), here and to me real MeanStacker, you should use AngularJS to do this step, but for sake of generalization and focus on the concept of (Client/Server) communication, i will use the most regular AJAX calls.

1 – Request Insert Film

Create the Followoing Class inside the Client JS file as a Client representation for the Film Model.

function Film(_Name, _Language, _Category) {
    this.Name = _Name;
    this.Language = _Language;
    this.Category = _Category;
}

Then Create a Function to Request the Remote NodeJS REST Inset function

function InsertFilms() {
    var Films = new Array();
    Films.push(new Film('Home Alone','English','Comedy'));
    Films.push(new Film('Night For Counting Years','Arabic','Drama'));
    $.ajax({
        type: "POST",
        data: JSON.stringify(Films),
        contentType: "application/json; charset=utf-8",
        url: "http://127.0.0.1:8080/Insert",
        dataType: "json",
        processdata: true,
        success: function (data) {
            alert(data);
        },
        fail: function (error) {
            alert(errors);
        }
    });
}

2 – Get ALL Films

function GetAllFilms() {
    $.ajax({
        type: "GET",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        url: "http://127.0.0.1:8080/GetAll",
        dataType: "json",
        processdata: true,
        success: function (data) {
            alert(data);
        },
        fail: function (error) {
            alert(errors);
        }
    });
}

3 – Gey By Film Name

function GetFilmByName(filmName) {
    $.ajax({
        type: "GET",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        url: "http://127.0.0.1:8080/GetByKey/"+filmName,
        dataType: "json",
        processdata: true,
        success: function (data) {
            alert(data);
        },
        fail: function (error) {
            alert(errors);
        }
    });
}

4 – Update Film

function UpdateFilm(filmName, filmObject) {
   $.ajax({
        type: "PUT",
        data: JSON.stringify(filmObject),
        contentType: "application/json; charset=utf-8",
        url: "http://127.0.0.1:8080/UpdateByKey/"+filmName,
        dataType: "json",
        processdata: true,
        success: function (data) {
            alert(data);
        },
        fail: function (error) {
            alert(errors);
        }
    });
}

5 – Delete Film By Name

function DeleteFilmByName(filmName) {
    $.ajax({
        type: "GET",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        url: "http://127.0.0.1:8080/DeleteByKey/"+filmName,
        dataType: "json",
        processdata: true,
        success: function (data) {
            alert(data);
        },
        fail: function (error) {
            alert(errors);
        }
    });
}

and we done, you can create an html page and test your code as you like , but usually don’t forget to run the Controller JS file before you start requesting it.