CategoryWebAPI

Don’t worry, Heimdall will watch over all your microservices.

TL;DR : I wrote a service registry tool, named Heimdall, go and fork it!

Long version: almost every time I am working on a piece of code I get stuck on something and after a while I get new ideas for new projects. This may lead to a huge number of useless git repos, each one with a partially functional software, but it also pushes me to work on new things each day.

This time I was working on a super-secret project (that I will of course share very soon) based on a nice microservices architecture and I soon realized I needed some kind of Service Registry. The project was quite small so I was not really interested in a complex tool like a router with load balancing functions or similia so I decided to code the thing myself.

For the ones of you that don’t know what a Service Registry is and what it does, allow me to give you some context.
Imagine you’re a client that needs to consume some APIs. You could of course use a configuration file for storing the endpoints but in case you’re cloud-based, urls can change often.

Also, what if you want some nice features like multiple instances, autoscaling and load balancing?

The answer is simple: use a registry! 

Every service will register itself during initialization, allowing clients to query the registry and know the endpoint (possibly the best one).

I found this concept pretty useful so I decided to create a poor man’s version myself, using ASP.NET Core, MongoDB and React and I named it Heimdall, the guardian god of the Norse mythology .
The list of features for now is very scarce, you can just register a service, add/remove endpoints and query, but I have a full roadmap ready 🙂

Oh and I also added help pages using Swagger !

Command Handlers return values in CQRS

I have recently came across this very interesting blog post by Jimmy Bogard ( the guy behind Mediatr, if you don’t know him). Talking about CQRS, he makes a good point about how the user should be informed of the result of a Command execution.

Should the Command Handler return a value?
Should the Command Handler throw an exception?

These are just some of the strategies we may take, another option could be just logging the operation and forget anything happened. Whatever.

A while ago I blogged about how to validate the Commands and ensure the data passed to the Command Handler is valid. This is the strategy I’m adopting in my projects lately. Why? Several reasons: first of all I want to keep Command execution separated from the validation, also Commands should be some sort of “fire and forget” operations. Let me clarify this a little bit.
In my opinion Command execution should be a boolean operation: the system can either execute it or not. Stop. I should be able to know ahead if a Command can be executed and that’s the validation phase. If I finally manage to get to the Handler, I know that the data I have is valid and I can run Command. No need to return a “true”.

So what should I do to make all the pieces fit?

  1. Use the Decorator pattern to ensure each Command Handler executes some sort of validation
  2. Analyze the Command and check its validity against business rules or anything else you want
  3. the Validator gives back a Validation result containing a (hopefully empty) list of errors
  4. in case something went wrong, throw a specialized Exception, for example something like this

Since most of the projects I am working on lately is composed of some sort of Web API based on .NET Core, I decided to create an Exception Filter that will eventually return to the user a JSON object with the details of the validation.

 

Bonus
Some of you may have noticed that some of the links in this post point to this Github repository, LibCore. It’s a small set of utilities I am writing, mantaining and using in my projects. I thought it would be useful to share the sources, maybe just to hear comments from the community. Food for thought.

Data pagination with NodeJS and React

TL;DR:

here’s the link to the GitHub repo.

Some time ago, in one of my articles I showed a way to paginate your data using WebAPI on the server and AngularJS on client-side. Funnily enough I wrote that post exactly two years ago, I just noticed it while writing this. Well, turns out a lot of people is still searching for it, so now, after two years, I have decided to write another couple of notes but with a different tech stack.

Yes, of course, I could have used the same backend from the old article, but where’s the fun in that?

Enter NodeJS and React!

So, let’s start with the server first. As you can see from the sources, I used Typescript this time. To be honest, I don’t feel “safe” while writing Javascript code, even with lots of unit tests. Having some form of “strongly-typed” language is a little bit of relief, at least for the .NET coder in me.

The architecture is very simple: we have an express application with just one Route ( /api/products/ ) exposing a GET action which reads from a Repository the paged list of available products. Due to the nature of the example, I decided to keep things simple and not add any kind of IoC container, just to avoid to overcomplicate the code.

I have also added two middlewares, one to console.log() all the incoming requests and the other to allow CORS for a specific domain ( eg. our client application ). In case you need to refresh your memory, here’s a nice article about NodeJS middlewares.

The core concept that you can see from the Products API is to return an object that exposes the list of Products along with some infos like the total number of pages, the total Products count and the current page number.

Let’s talk about the client now.

I was definitely not disappointed discovering that the learning curve for React is actually very, very low. Coming from the Angular world, I was expecting more difficulties, but in a matter of hours I have been able to setup my dev env with Typescript ( wanna know how?  ) and start coding my components.

Oh yes, don’t miss my webinar this Saturday! I’ll do a quick introduction about Typescript and React.

Ideally, I could have served the client part directly from the NodeJS application, but I preferred to keep everything separated. Yeah, I had to activate CORS, but it’s not really a big deal. Also, it makes everything more “microservices-oriented“, which is becoming more and more an hype these days. In my mind, for that kind of architecture you should have two servers talking, but bear with me.

In our small demo, the client is using a service to read the products, displays them in a table and renders a pager at the bottom. As you can easily notice, I am using the fetch() polyfill to perform the AJAX request.

Also, to make things more interesting, in this case I am using an IoC container, Inversify, to handle dependencies. However, since Components are instantiated directly by the React engine we cannot use constructor injection but have to revert to property injection….which in this case is handled by the @lazyInject decorator. I’ll write another post about the subject in the upcoming future.

For now, if you enjoy the example, don’t forget to write a comment!

CQRS: on Commands and Validation

Let’s have a quick discussion about CQRS. There’s a lot to say to be honest, so let’s try to focus on just one thing today: validating your Commands (who knows, I could start a series after this, we’ll see).

The idea is simple: how can I make sure that the data I am passing to my Command Handler is valid?

Also, what is the definition of “valid” ?

There are several aspect to take in consideration, several “levels” of validation. I could just make sure the Command object is not null and/or the data it contains is not empty. Or I could run the validation against some kind of context and check the application Business Rules.

As you can imagine, having different levels means that we could have different implementations scattered in various places/layers of our architecture. For example I could have the API Controller (or whatever outmost layer you have) check for null and perform some Business Context validation later, before or directly in the Command Handler.

In my last project however, I decided to keep things simple and keep my validation in just one place.

Initially the right spot was the Command Handler itself, but of course this would have violated the SRP.

A quick and immediate solution was to have a separate instance of a IValidator<TCommand> injected in the handler. Easy.

Then I realised that my handlers are more “close to the metal” than expected: in most of the cases they access directly the DAL (passing through some kind of IDbContext) and I didn’t wanted to rewrite the call to the IValidator in case I had to switch the persistence layer.

Luckily enough, there’s a nice pattern that came into rescue: the Decorator! As explained very clearly on the SimpleInjector docs, you can create a ValidationCommandHandlerDecorator class, inject an IValidator<TCommand> and let your IoC do the rest.

Maaaaagic.

Bonus tip: in some cases you may want to skip completely the validation. Maybe you have a very good reason or maybe you’re just lazy. Whatever.

In this case, all you have to do is to write some kind of NullValidator<TCommand> class and instruct your IoC to use it when a specific validator is missing for that Command.

Dell Limerick Hackathon 2016

Hi everybody!

Last January we had an Hackathon here @ Dell Limerick, the main theme was “office productivity”, aka “how would you improve your and your coworker’s productivity”.

I was in a team with other 4 very smart guys, didn’t won but all in all it was a terrific experience…two days straight of brainstorming and coding madness combined with pizza and energy drinks.

The winners came up with an interesting prototype of a chat bot running as Lync addon that can answer every type of question, from “how’s the weather” to “who broke the last build?”, passing from “tell me about story 1234567”. I can’t go too deep in the details (also, lots of natural language analysis is involved) but it was definitely a very, very interesting project and really deserved to win.

My team instead…well we produced a voting platform for ideas. In a nutshell, every user registered to the community can post his ideas (which can be divided into macro-areas) and the others can vote it using points they have received when registering. If an idea is approved, the voters will get back the points and a small bonus. If an idea is cancelled instead, they will get the points back (but no bonus).

It was a cool project to work on, we used a very simple micro-service CQRS architecture running on AngularJS, WebApi and MongoDB. Oh and everything was hosted on Azure.

After the contest, we decided to release all the sources, you can find them on my GitHub repository.

Enjoy!

© 2017 Davide Guida

Theme by Anders NorenUp ↑