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
...
}
}
Assets Used
In the assets folder, I define the mock-data in the following path ...
assets/mock-data/api/
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,
...
}
}
This file is imported as such.
import config from '@core/config.json';
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([]);
}
};
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",
}
}
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.