Design API layer
Introduction:
- This is an example for layer for API like REST
- Each API method should have separated javascript method
- We have two backends: main and reserved, and sometimes we can switch between them.
The API for this example:
GET /posts
— List of all postsGET /post/:id
— Read single post by IDPOST /posts
— Create new post, require authorizationPUT /post/:id
— Edit created post, require authorization
Let's design API for JavaScript developers:
Okay toplevel API is done. Let's deep dive into underlevel.
Attach and call it
We have two methods that requires authorization(postCreate
, postEdit
) and two simple(postsList
, postRead
).
How can we store authorization information? For example we should have some kind of authorization token
First of all, we define basic API methods, to call our backend:
You can explicitly define effect.done
type using something like typed-contracts to generate types from runtime validators. But here it is not neccessary.
Also NetworkError
and AccessRestrictedError
are custom classes that extend Error
, that should be used to handle custom errors on different layers (you can use any paradigm).
Okay, requestFx
can be used to request any data using POST
, GET
and PUT
with body as json object. Now you need to define method, that uses backend uri and token.
Now we have two service effects to call non-authorized and authorized methods. Let's use it to create methods from introduction 2.
As you can see, original postEdit
has two arguments, but effect can have only one. That's because we need to wrap arguments to object with explicit argument names.
Now you can add listeners to requestFx
, requestInternalFx
and requestAuthorizedFx
to handle all request calls created with attach()
. It can be handy when you create requests loader of some kind.
For example: