DEV Community

Apiumhub
Apiumhub

Posted on • Originally published at apiumhub.com on

How do I create a Fake Server with Dyson?

This article may seem essential for a frontend developer, but for me it was a sensational discovery. To understand what motivates this article, let me introduce my context: I had always developed backends, but two years ago, when I got started at Apiumhub, also I have started developing frontends. So far, I have been following the path that every frontend developer follows, from the most basic layout to more complex architectures like ngrx.

During my journey I have seen the advantages and disadvantages of frontend development. The tool that I will focus today seems a fantastic solution to be able to disengage from backend when developing. I had already suffered a dependency from the backend side (resulting in pressure to finish a development phase to be able to unlock the frontend implementation on an application).

Without going any further, let me show you, using an example for dummies, how to introduce the Dyson tool to create a fake server to serve, in this case, a Frontend implemented in Angular 10.

What is Dyson?

Dyson is a node server for dynamically serving JSONs. It allows very intuitive javascript file generation of JSON responses.

As they explain in their documentation, Dyson is based on a simple configuration of an object consisting of a path and a template.

Step by Step

First of all, we are going to import all the packages we need to our Angular project using our package.json. We’ll add both packages to our dependencies object:

  • “dyson”: “^3.0.2”
  • “dyson-generators”: “^0.2.1”

Dyson generators is a tool that will help us generate random data such as Ids or Names, for example. In its documentation you can find all its utilities.

Once the dependency has been added and installed using the “ npm install ” command, we can proceed to Dyson setup.

Creating the working directory for Dyson

In the project’s root folder, we are going to add a new directory to which we will call, for example, “mock-server”:

Setting up your first endpoint

We will configure a basic call “/health”, which returns a json with the message “green” and an id generated in each call. This is a typical call to test the communication between a front server and a back server.

I like to group the calls by domain in separate directories, so we will create a “health” directory and a “get.js” file, referring to the method we will use for the call within the health domain.

Next I show you the code to set up endpoint’s configuration:

const g = require('dyson-generators');
module.exports = {
  path: '/health',
  method: 'GET',
  template: { 'id': g.id(), 'message': 'green' }
}

Enter fullscreen mode Exit fullscreen mode

*Get the Server Running *

Get the server running is as simple as running the command “ dyson ./mock-server ” pointing to the directory where we’ve created all the Dyson configuration:

We will be able to see how the endpoint we have configured is registered.

Dyson runs by default on port 3000, so if we try from our browser to attack the endpoint 127.0.0.1:3000/health we should see the following:

We already have the certainty that the fake server is up and running and well configured. Now we have to do the most important thing, to make our app communicate with it.

Communicating our app with the server

To communicate our app would be as simple as using the Angular http client and pointing directly to the url we have put in the browser using a GET method.

This is not very useful, because we are pointing port 3000 to the client, and that means won’t be scalable when we want to change the environment and point it to the real backend.

What we’re going to do is set up a proxy and raise the application using that configuration.

{
  "/health": {
    "target": "127.0.0.1:3000",
    "secure": false,
    "changeOrigin": true,
    "logLevel": "debug",
    "pathRewrite": {
      "^/": ""
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

As shown in the image, we have made a simple configuration in JSON indicating that every endpoint carrying “/health” should be redirected to “http://127.0.0.1:3000”.

Once the proxy document is configured, we will make a basic page containing a button that executes a call to the backend, to the path “/health”. Then, the proxy will point to the fake server.

This would be the basic code:

callToBackend(): void {
    this.httpClient.get('/health').subscribe((jsonRepsonse: any) => {
      this.responseContent = jsonRepsonse.message;
      this.responseId = jsonRepsonse.id;
    });
  }

Enter fullscreen mode Exit fullscreen mode

This is a call to /health without specifying the full url, just the path, the proxy configured above will redirect to the Dyson server. In addition, we have made a basic html with a button in order to test the full flow from the browser:

Starting the application

To start the application, we’ll have to open another different terminal where we have the Dyson server running, to be able to run our Angular application. To do this, we’ll run the command specifying the proxy file created earlier to specify the path that should point to the Dyson server:

**_ng serve –proxy-config proxy.conf.json_**

And then we only have to test the application. We will be able to visualize the data served by the server. In addition, in the terminal in which we run Dyson, a trace can be seen as the communication has been made, as it is shown in the following images:

Bonus Track I: Automatic Update

But Dyson has a little con. If we are designing the communication contract with the api, as we develop, every time we update Dyson’s configuration in our javascript file, we will have to stop and start the server.

To avoid this, there is a tool, also based on Node, that check the js files of a Node server and restarts it automatically if any file changes.

That tool is called nodemon and you can review its documentation for more details.

To include it in our Angular project, it is as simple as including the dependency in the package.json:

“nodemon”: “^2.0.3” ,

And run **npm install** in the terminal.

If we execute the following command: nodemon –watch mock-server –exec dyson mock-server , and then change a part of the configuration of our Dyson server (in this case we’ll change the message green by network), we’ll be able to see in the terminal how the server configuration is updated, and we’ll see how the response we get from the browser, is the new one, without having to restart the frontend application.

const g = require('dyson-generators');
module.exports = {
  path: '/health',
  method: 'GET',
  template: { 'id': g.id(), 'message': 'red' }
}

Enter fullscreen mode Exit fullscreen mode

Bonus Track II: Dyson Server Dockerization

Some time ago, two colleagues from Apiumhub created an image to dockerize the Dyson server, having the “watcher” that allows automatic data refresh. This would make it much easier to set up the server’s parameters, and it is possible to configure it when the command line that lifts the container in the terminal is executed. You can find all the details in DockerHub.

Conclusion

As you may have seen, it is a very simple tool. Nevertheless, in my opinion, it brings a lot of value in the day to day of any frontend developer, since it removes the limitation of an external dependency to be able to develop avoiding most of the blockages in the implementation of an integration with an external API that is still under development.

The post How do I create a Fake Server with Dyson? appeared first on Apiumhub.

Top comments (0)