Microservice Architecture & Angel Framework

Highly Extensible, Full-featured Server Side Framework in Dart

Microservice Architecture & Angel Framework

Hello folks! I’ve spent some time playing around with Dart since my last post and I’ve involved myself in another experiment. This time, I decided to create a Restful API and Server Side APIs using Dart programming language.

For those who don’t know what Dart is, It is a programming language which is easy to learn and is used for building user interface as well as backend API’s. Need more details about dart? click here.

Now, lets directly jump into Microservices.

What is Microservices ?

Microservices has become quite a buzzword in recent days. Theoretically, it is also known as Microservice Architecture. It is an architectural style that structures an application as a collection of services that are:

  • Highly maintainable and testable.
  • Loosely coupled.
  • Independently deployable.
  • Organized around business capabilities.
  • Owned by a small team.

Best example for microservices architecture is a Security firewall application where we can use this as an independent module in any of our applications. Many businesses face growing infrastructure costs caused by the way their current architecture operates. Making any kind of change to an application in a monolithic architecture can be expensive because every part of the monolith interacts with other parts — so a change in one place affects other aspects. This means a lot more work for developers and operations professionals to sort out the side effects of updates before they can make them. More updates means the bigger the monolith grows and the more time and resources have to go into making future changes.

What is Angel?

Angel is a highly extensible, fully featured server side framework built in Dart. It is designed with extensibility in mind, so even when we need a feature that’s not officially supported, we can easily implement it by creating our own plugin/package. It has first class client support for web, flutter and VM.

It has features like hot reloading, Controllers, Dependency Injection & ORM. It has the direct support for GraphQL, MongoDB & RethinkDB. It also provides support for server-side templating, WebSockets, authentication, and much more.

Request Life Cycle of Angel

Requests in the Angel framework go through a relatively complex lifecycle, and to truly master the framework, one must understand that lifecycle. The complete lifecycle is mentioned below chronologically:

  1. startServer is called.
  2. Each HttpRequest is sent through handleRequest.
  3. handleRequest converts the HttpRequest to a RequestContext, and converts its HttpResponse into a ResponseContext.
  4. angel_route is used to match the request path to a list of request handlers.
  5. Each handler is executed.
  6. If res.isDetached == false, all headers, the status code and the response buffer are sent through the actual HttpResponse.
  7. Finally, the HttpResponse is closed.

Middleware of Angel

Sometimes, it's a requirement to recycle code to have it run on multiple routes. Angel allows this in the form of middleware. Middlewares are frequently used as authorization filters or to serialize database data for use in subsequent routes. Middleware in Angel can be any route handler, whether a function or arbitrary data. We can also use middleware to deny/accept request and to throw exceptions.
Here’s an example of how to use a middleware:

var authorizationMiddleware = chain([
  banIp('127.0.0.1'),
  requireAuthentication(),
  ensureUserHasAccess(),
]);

var someOtherMiddleware = chain([
  (req, res) async => true,
  takeOutTheTrash(),
]);

var theActualRouteHandler = (req, res) async {
  // Handle the request...
};

app.get('/the-route', chain([
  authorizationMiddleware,
  someOtherMiddleware,
  theActualRouteHandler,
]);

Example for Angel Controllers:

import 'package:angel_framework/angel_framework.dart';

@Expose("/todos")
class TodoController extends Controller {

  @Expose("/:id")
  getTodo(id) async {
    return await someAsyncAction();
  }
  // You can return a response handler, and have it run as well. :)
  
  @Expose("/login")
  login() => auth.authenticate('google');
}

main() async {
  Angel app = new Angel();
  await app.configure(new TodoController().configureServer);
}


                    --------------------------


class Expose {
  final String method;
  final Pattern path;
  final List middleware;
  final String as;
  final List<String> allowNull;

const Expose(Pattern this.path,
      {String this.method: "GET",
      List this.middleware: const [],
      String this.as: null,
      List<String> this.allowNull: const[]});
}

Installation:

Prerequisites

  • Firstly, ensure you have the Dart SDK installed.

Now, let’s install the Angel CLI, including several code generators and commands that will help you expedite your development cycle.

pub global activate angel_cli

Next, let’s create a sample project, called firstAPI.

angel init firstAPI

This will ask you to choose one of the templates among the available options. I have selected GraphQL template and you can choose according to your requirement. It creates a folder called firstAPI, and copies the Angel boilerplate into it. If you wanted to initialize a project within the current directory, instead of making new one, you can use the following command:

angel init

Voila! We have created our first project in Angel.

Next, we need to know how to run & test it.

It’s as simple as counting on your fingers. Use the following command to run the project:

dart --observe bin/dev.dart

# Use the `--observe` flag to enable hot reloading in Angel.
# Use dev.dart for development and for production prod.dart

Using Angel is as simple as that.

I hope you liked the article and I will keep experimenting with new things and will come up with some amazing articles on my findings. Stay tuned! ?. 

You can access all my experiments related to Angel on my GitHubIf you liked this quick walkthrough and my experiments in Github then give a star to the repo and also press and hold the clap for a couple of seconds ? ? ?.

Thank you. It’s time for you to find your angel using the Angel framework ?. Bye Bye.

2020 © All rights reserved. GeekyAnts India Pvt Ltd.