Creating a simple api mock service in Aurelia-cli

Introduction

In the last weeks I faced the challenge, that our central development API had several bugs so that I was not able to request it. So I created a simple mock-service in aurelia-cli.
Besides the fact that the mock-service enabled me to work on, this setup has the big advantage, that the development environment is now completely independent.

Following a rough guide, how I created the mock service.

How To

Add aurelia-configuration plugin to project

First, I added the aurelia-configuration plugin to my project. Besides the advantage that this component enables me to have all configurations in one central place, I am now able to have stage dependent configurations and I don't need to care about staging anymore.
  1. Install aurelia-configuration by running "npm install aurelia-configuration --save"
  2. Configure plugin in main.ts
 .plugin('aurelia-configuration', config => {
        config.setEnvironments({
            development: ['localhost', 'dev.local', '127.0.0.1'],
            staging: ['staging.myproject.de', 'test.staging.myproject.de'],
            production: ['myproject.de']
        });
        config.setDirectory('config'); 
        config.setConfig('config.json'); 
    })
The main.ts configuration defines, that I want to have the three stages "development", "staging" and "production" reachable under the set urls. The aurelia-configuration plugin is now able to identify the current host (e.g. localhost) and automatically provides the right configurations.

In addition to the stages I tell the plugin where the configuration file can be found.

Create configuration file

For the integrated aurelia-configuration component I also created the central configuration file (myproject/config/config.json) where I added a section for my routes for each stage:

{
  "name": "MyProject",
  "api": {
      "key": "somekey",
      "endpoint": "http://www.google.com/"
  },
  "development": {
    "myproject-api": {
          "key": "developmentonlykey938109283091",
          "endpoint": "localhost:9001/api/v1",
        "api-headers": {
        "Content-Type": "application/json"
      },
      "routes": {
        "users": {
          "postUserRegister" : "/users/register.json",
          "getUserIndex": "/users/users.json",
          "getUser": "/users/get-user.json",
          "getUserAddress": "/addresses/get-address.json"
        }
      }
    }
  },
  "production": {
    "myproject-api": {
        "api-headers": {
        "Content-Type": "application/json"
      },
      "routes": {
        "users" : {
          "get-user-index": "/users/",
          "get-user": "/users/{user-id}",
          "get-user-address": "/users/{user-id}/address"
        }
      }
    }
  },
To get the list of routes a little bit clearer, I additionally grouped them in subcategories (users). For development I added direct paths to the respective response-json.files.
For the other stages I added the url-paths.

Create folder structure and response json files

Each route needs to have a request. In my local development environment this routes are direct paths to the respective json files. So, my folder structure looks as follows:

  • myproject
    • api
      • v1
        • users
          • users.json
The users.json file represents the user object:

{
    "user": {
        "firstname": "Max",
        "lastname": "Mustermann
    }
}

Adjust Http Request

Finally, having the structure set up, the request now should look as follows:
export class UserService{
  readonly configRoutesPath : string = 'myproject-api.routes.users';
  private baseApiUrl : string;
  private apiRoutes;

  constructor(
      private HttpClient: HttpClient,
      private config: AureliaConfiguration
  ){
      this.baseApiUrl= this.config.get('myproject-api.endpoint');
      this.apiRoutes = this.config.get('myproject-api.routes.users');
  }

/**
   * Requests the user index from API
   */
  public getUsers() : Promise<Users>{
      let users : User[] = [];
      this.HttpClient.fetch(this.baseApiUrl + this.apiRoutes.users.getUserIndex, { 
          headers: this.config.get('myproject-api.api-headers'), 
          method: "GET"
       })
      .then(response => { return response.json()})
      .then(data => { return data.users; })
      .catch(err=>{ throw "Something went wrong on requesting the API for getting users, " + err; });
  }
In constructor I load the routes from configuration path. This routes are used for each http request.

Conclusion

This is my current setup how I'm mocking the api. Hope this quite rough guide can help you or can give any ideas. If you have any other Ideas, hints or feedback please do not hesitate to write a comment ;)

Due to time problems, I had not that much time for writing a more detailed tutorial with more explanations. Please bear with me ;)

Comments

Popular posts from this blog

Connecting native Database-Client to Docker SQL-Container using Docker-Toolbox

How to create a custom Task using Aurelia-CLI