Angular Development mocking External Calls

bob.ts - Sep 27 '21 - - Dev Community

On a previous client project, I saw a use of local JSON for quick development that was horrible in that particular definition. I've refined the definition into something I can use more efficiently.

Angular Configuration

First, in the tsconfig.json file at the root of the project, I clean up the imports and allow JSON files to be resolved on import, as shown ...

{
  "compilerOptions": {
    ...
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true
   ...
  }
} 
Enter fullscreen mode Exit fullscreen mode

Assets Used

In the assets folder, I define the mock-data in the following path ...

assets/mock-data/api/
Enter fullscreen mode Exit fullscreen mode

For this article, assume there is a users.json file in the api folder.

Project Configuration

Within the project, I create a config.json file that can be imported.

{
  "features": {
    ...
    "useLocalJSON": false,
    ...
  }
} 
Enter fullscreen mode Exit fullscreen mode

This file is imported as such.

import config from '@core/config.json';
Enter fullscreen mode Exit fullscreen mode

By referencing config.features.useLocalJSON, we can quickly determine if we are using the local JSON files or calling out to the appropriate API endpoint with a single-line toggle.

Use of useLocalJSON

Here's some of the code in my api-service.

import hostnames from '@core/constants/hostnames.json';

...

getURL = (key: string): string => {
  if (this.useLocalJSON) {
    return hostnames.localJSON.BASE + hostnames.localJSON[key];
  } else {
    ...
  };

  getUsers = async (): Promise<Array<User>> => {
    const key: string = 'get-users';
    const url: string = this.getURL(key);
    try {
      const users: Array<User> = await this.http.get<Array<User>>(url).toPromise();
      return users;  
    } catch (error) {
      this.triggerErrorMessage(error);
      return Promise.resolve([]);
    }
  };
Enter fullscreen mode Exit fullscreen mode

As yo can see here, the getURL function assembles the URL based on the key from the hostnames.json which looks something like this.

{
  "localJSON": {
    "BASE": "assets/mock-data/api/",
    ...
    "get-users": "users.json",
  }
}
Enter fullscreen mode Exit fullscreen mode

Summary

So, with all this code we are able to serve the code and with a single feature flag, start using local responses rather than pure API calls. This allows me to work ahead of the backend team, or accommodate issues in the development environment, such as the API endpoints being down.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .