Build an event service using Nest.js
In this tutorial we will build a service using nest.js which will function as a way for us to quickly extend functionality to a particular event that occurs within our application.
The concept of this is very similar to a message broker like RabbitMQ however, instead of a publish/subscribe model, we will be implementing a fire and forget service which receives an http request and sends out multiple http requests in response.
The use-case
The idea behind this is to keep our core service fast. Instead of performing many actions at once, we just perform the necessary ones and let the event service handle the rest.
As you can see from the diagram above, we have split our services into 3 parts, Core, Analytics and Email. Analytics and Email services can take time to execute and so we want them to be handled in the background. Therefore we place the Event service between the other services. The Pink arrows represent what we will be building.
What we will be doing
Please note that this will not be a production ready solution, this is purely to illustrate the concept of how you could build one yourself. If you would like a full deep dive of this then please let me know in the comments.
Firstly we need a database. For this we can use SQLite with Prisma.
We will be building and exposing three endpoints:
POST /events
Creates a new event record in our database.
POST /events/:id
Triggers the event and runs all actions associated with that event
POST /actions
Creates an action record in our database
Additionally we will be required to use axios via the HTTP Module.
We will also need to install and setup the Event Emitter.
The Implementation
First things first we will set up our database schema. In your prisma/schema.prisma file add the following models:
Now we will create the event service.
As you can see this contains a method to create a new event as well as trigger an event therefore invoking the actions of that event. We use the event emitter in order to pass the processing of the event to the service therefore we do not need to wait for a response from our Core Service and all of our processing can happen in the background.
Summary
As I mentioned before this is just a rough idea of how the event service works. There are many additional pieces that can be included here such as process tracking and error fallbacks.
If you would like a full example explaining how to create a production ready event service then please let me know in the comments.
Until then… Happy hacking!