Middleware
In the client, there are also middlewares similar to Milkio that can execute arbitrary logic before or after sending requests to Milkio.
For example, in our login feature, we usually use schemes like JWT to implement it. This requires us to add a token in the header of each request to prove the user’s identity, and the token may change over time. Client middlewares can help us encapsulate such functionality and automatically add the appropriate token to each request. Of course, this is just the most common usage of middlewares in the client.
Usage
Open your /src/packages/client/milkio.ts
file and you can write the middleware as shown below. You will find that its syntax is almost the same as the middleware syntax in Milkio.
Since the environment in which your client runs is uncertain (although it mostly runs in a browser, you will need it in the future), please use the storage
parameter in the method to store data such as tokens. Its usage is the same as localStorage
, the only difference is that its return values are all Promises, so you need to add await
in front of them.
Adding Middleware in the Client
In addition to providing built-in middlewares directly to the client in your Milkio project, you can also add middlewares in your web project. In your client.ts
file in the web project, you can add middlewares like this: