Evolution of a Node.js API, Zoe.js — Controller Layer

Adams Academy
3 min readJul 23, 2020

--

In the Controller layer application receives a request, creates a request object, calls the service layer and returns with the response.

What we’re going to do now is to implement the skeleton of the Product controller and router. Besides that we also starting to create an API documentation what is really a description for a Visual Studio Code extension Rest Client.

Product Controller

With this section we’re starting to write our API code, so I create a new api directory under the app folder. Every resource will have a separate directory under the api folder.

Product resource specification

Let me copy the Product resource specification here from chapter 6.

  • Read products — GET /products
  • Create a product — POST /products
  • Read a product — GET /products/:id
  • Update a product — PATCH /products/:id
  • Delete a product — DELETE /products/:id

product_controller.js

Based on the specification we need all the CRUD operations for the Product resource. In our Product Controller object there will be a specific method for each and every CRUD operation.

Zoe.js follows Ruby on Rails controller actions convention.

  • indexGET /products
  • createPOST /products
  • showGET /products/:id
  • updatePATCH /products/:id
  • destroyDELETE /products/:id

Now let’s see the actual app/api/product/product_controller.js skeleton code.

Product Router

Product router is in app/api/product/product_router.js

Every CRUD operation has its matching product controller method pair in the product router.

Finally we need to register Product routes in the app/config/app.js file.

VSC Rest Client

Visual Studio Code has a Rest Client extension which allows you to send HTTP request and view the response in Visual Studio Code directly.

In the picture above, on the left side I just send a GET {{baseUrl}}/products HTTP request and you can see the HTTP response on the right side.

Rest Client requests live in .http files. In this file you can describe your requests with URLs, HTTP methods, HTTP headers and the request body. Sending a request happens when you click on the Send Request line. I created a new doc directory under the root folder, and there's my products.http descriptor at doc/products.http.

Rest Client supports variables (for example @baseUrl) and environment variables as well (for example {{protocol}}). For creating a Rest Client environment you need to edit your .vscode/settings.json file.

In this file we have a development environment with 3 variables. And there's also an option to share variables between environments under the $shared property.

--

--

Adams Academy

Adams Academy helps you to cut through the noise and understand programming languages, web development with simple programming tutorials.