Evolution of a Node.js API, Zoe.js — Service Layer
Service layer manages business logic and data access. It abstracts tasks and hides the implementation.
In general, I can say when you have a chance you should reuse your software components. A service class is a great example for reusability, it does a specific thing and it has every information and dependency to perform its task. Therefore you can easily call your service class from a console command, from a socket connection or from any given piece of software module.
Usage
Usually I use service classes two ways, but I never mix these.
One usage is when I have a “god” service class for each module, and in that service class I have multiple tasks/services. Drawback here is these tasks can have a bunch of dependencies and this “god” service class can be too big. For example: ProductService
The other usage is when I have specific service classes for each and every tasks in the system. This way I can see all the possible use cases in the application and dependencies are scoped to that one service class. For example: AddProductToCart
.
For this sample project I’m totally okay with 1 service class because I don’t have too many or too complex business logics. Your choice should depend on your needs as always.
Event Emitter
With an Event Emitter
you can raise an event somewhere in your application, and you can listen to that event somewhere else in an Event Listener
.
Suppose that you need to send an email when somebody orders a product. Ordering can happen via the web site, via the API or via an Excel import. When one of the use case happened, you raise an OrderIsPlaced
event with the Order information, and in an OrderIsPlacedListener
you can handle the event, there you can send the email.
For emitting an event there’s an emit
method, first argument is the event name, the remaining are the event arguments. With on
method on the Emitter instance myEmitter
you can listen to events. In the example above I raised OrderIsPlaced
event 2 times.
Product Service
For every CRUD
operation we have a separate method in the ProductService
class. This can seem overengineering or boilerplate code, but if you have complicated business logic, complex validation or you need to reuse your logic, then this extra code can worth the plus effort. For the sake of consistency I use service layer for every operation even for the simple ones.
Every service extends the EventEmitter
class, so we have the option to raise events from anywhere inside a service class.
Source Code
Next chapter
Soon
Chapters
Adams Academy
theadamsacademy@gmail.com