Data loading: building an SDK

The first thing we're going to need to do is build a JS SDK for accessing our API.

Our JS SDK is a separate project. This project interfaces with our API on our projects behalf. It's the sole place which makes AJAX calls to our API - kept away from our UI project.

Why?

This ensures that:

  1. Our actions are decoupled from our API. They call the SDK – not endpoints directly.
  2. The SDK can be tested alongside our API; if the API responses change shape unexpectedly our SDK can fail tests. This means that we have zero surprise breaking changes across teams. And we can test this separately from our UI tests.
  3. The SDK can implement data mocking transparently to our UI code
  4. Mocking via our SDK means we can use hot reloading and ignore proxying requests to our API
  5. SDK mocking and tests are self-documenting and can be reused across projects

All said, creating a separate SDK makes things easier to code (via hot module replacement), easier to test and easier to share. Let's start by building one for our API.

Building the SDK

Best practices

We have three best practices for building an API:

1. Use superagent and callbacks to manage async logic

This is a nicer way of saying "don't use promises". Promises consume errors which makes your code much harder to work with. Also, we're going to write some redux middleware to automatically track the status of our AJAX calls from the SDK. Working with callbacks here is much easier than workign with promises.

2. Each API call should be one SDK call

We'll keep control flow, such as linking two API calls, within our actions. If two calls need to be tightly coupled within the SDK you've probably got a faulty API design.

3. Normalization should happen within your UI project in Normalizr

The API should be response-agnostic. We'll handle normalization of the API response within our UI code.

Writing the SDK code