Skip to content
当前有符合你浏览器所设置语言的版本,是否前往zh-CN版本的网站?
There is a version suitable for your browser's language settings. Would you like to go to the zh-CN language of the site?
HomeDocument

Middleware

H1

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.

export * from "./types";
import { failCode } from "./project/src/fail-code";
import type ApiSchema from "./project/generated/api-schema";
export { defineMiddleware } from "milkio-client";
import { defineMiddleware, defineMilkioClient } from "milkio-client";
const middlewareA = defineMiddleware({
bootstrap() {
// When your client is initialized
},
beforeExecute({ path, storage, params, headers }) {
// Operation before sending your request
},
afterExecute({ path, result, storage }) {
// Operation after sending your request
},
});
export const createClient = defineMilkioClient<typeof ApiSchema, typeof failCode>([
// Add middlewares
middlewareA(),
]);
export const FailCode = failCode;

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:

export const client = createClient({
baseUrl: "http://localhost:9000/",
storage: localStorage,
middlewares: () => [middlewareA],
async handler(url, body, headers) {
return await (await fetch(url, { body, headers })).text();
},
});