Evolution of a Node.js API, Zoe.js — Layering
Zoe.js
uses a simple but powerful layering system. You don't have to implement all the layer in every case, you should implement those layers what you need. However it might be a good use case to have all the layers even if you don't need it, in this case you'll end up a consistent code base and you'll know where to find what.
- Actor sends a request
- Request object is created in the controller layer
- Controller layer calls service layer
- Service layer calls database layer
- Database operations
- Database layer returns in the service layer
- Service layer returns in the controller layer
- Controller layer creates a resource
- Controller layer creates a response from a resource
Actor
Actor can be anything which sends a request to the application. For example another program, another API or a Rest client.
Request (object)
Request object encapsulates and validates all the mandatory and optional request data, so you can see what properties a request can have. Furthermore when you use the request object you can be 100% sure that all the data are valid.
Controller layer
A Controller class receives the request, creates the request object, calls the service layer and returns with the response.
Service layer
A Service class can do basically anything such as calling the database layer, calling a 3rd party API and so on.
The purpose of the service layer is reusability. Think of a specific business logic what lives in a service class. There can be a case when you’d like to expose this business logic via the HTTP API and via a Console command. In this situation a service class ensures you about the reusability, you just simply call the very same service method from the API and from the console command.
Database layer
In the database layer we’re going to have models. Models store the schema and methods on the particular model. So a Model contains the Entity and it’s also a Dao
(Data Access Object).
Resource (object)
A Resource object is about data transformation, it sits between the Controller Layer and the (Json) Response as a transformation layer. In a resource object you can decide what you want expose as a response and in what format.
Response (object)
Controller object returns with a response object which goes back to the Actor for the given request.
Next chapter
Chapters
Adams Academy
theadamsacademy@gmail.com