Design API layer
- This is an example for layer for API like REST
- We have two backends: main and reserved, and sometimes we can switch between them.
The API for this example:
GET /posts— List of all posts
GET /post/:id— Read single post by ID
POST /posts— Create new post, require authorization
PUT /post/:id— Edit created post, require authorization
Okay toplevel API is done. Let's deep dive into underlevel.
Attach and call it
We have two methods that requires authorization(
postEdit) and two simple(
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.
AccessRestrictedError are custom classes that extend
Error, that should be used to handle custom errors on different layers (you can use any paradigm).
requestFx can be used to request any data using
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
requestAuthorizedFx to handle all request calls created with
attach(). It can be handy when you create requests loader of some kind.