Centralizing HTTP Requests

Why is it important to centralize HTTP API calls? Cory explains all.

Demo: Fetch

In this demo Cory sets up fetch and centralizes the HTTP calls.
He says we can think of this as like the repository pattern but in JavaScript: instead of abstracting away a database we abstract away the HTTP API.

We see some code which populates a table to users using our API call. We also create a unit test for it.

Our table of data loads successfully and in Chrome Dev Tools we see an XHR request of type fetch worked correctly.

Selective Polyfilling

It uses the user agent string to determine if the user needs a polyfill or has support for the native functionality.
If the browser has support for the feature then the pollyfill CDN just returns an empty response.

This was written by the Financial Times.
If you are interested in contributing to this (IMHO very worthy) project the Financial Times is offering 1 month’s free premium access to all FT content (normally $50) if your pull request gets merged in their repository.

Why Mock HTTP?

Cory uses Mock HTTP in his React and Redux course. Here he explains 6 reasons why this is desirable.

How to Mock HTTP

Cory briefly introduces Nock and then discusses using a static file of JSON encoded data as an alternative.

He mentions api-mock and JSON server (says he uses JSON server) to simulate a working API, as well as JSON Schema faker for generating fake data for you.

He says for the most power we might want to use a development webserver such as Browsersync or Express (see Part 4 for details on these).

Our Plan for Mocking

We have a three step plan, putting some open source projects to good use:

Demo: Creating a Mock API Data Schema

Demo: Generating Mock Data

We create a new file generateMockData.js and import from ‘json-schema-faker’.

In package.json we add the new script “generate-mock-data” to invoke our new generateMockData.js with babel-node.

We see the “Mock data generated” success message and a db.json file is created with our data in it.

Demo: Serving Mock Data via JSON Server

We add a new “start-mockapi” script to watch for changes in our db.json file.

The generated mock data gets served up over HTTP on a mock API.

Cory explains that random test data is very useful, so next we set it up to generate new mock data every time we run the app.

We pretend that our mock API is a real one and create baseUrl.js to point to the correct base URL in each environment.

We see that our app is hosted on port 3000 and our mock API is hosted on port 3001. But the delete links do not work.

Demo: Manipulating Data via JSON Server

We want to prove that we can save changes to our mock data.
Here we add the necessary code into index.js and are able to delete each user.
In Chrome Dev Tools we see each call to our mock API, and see that the data is removed from our db.json file.