Modern.js's BFF supports different runtime frameworks, currently Modern.js's BFF supports two runtime frameworks: Express.js and Koa.js.
Under the function writing, only the middleware writing method of various runtime frameworks is different, and other implementations are basically the same. Take Express as an example to introduce how to write a middleware by hand in the api/_ app.ts
and add permission verification:
Then add a normal BFF function /api/hello.ts
:
Finally, add the access code of the interface in the front-end src/App.tsx
, and call it directly in an integrated way:
Then exec pnpm run dev
starts the project, and accessing http://localhost:8080/
will find that the request for'/api/hello 'is blocked:
Finally, modify the front-end code src/App.tsx
to call the login interface before accessing /api/hello
:
Refresh the page and you can see that /api/hello
was accessed successfully:
The above code simulates the way to add middleware to the /api/_app.ts
to achieve an easy login function. Also, other functions can be implemented in this hook file to extend BFF Server.
Under the framework writing, Modern.js does not collect middleware in the api/_app.ts
, and the running process is controlled by the plugin itself.
The framework writing of Express supports defining the startup logic of API Server in api/app.[tj]s
. performing the initialization work of the application, adding global middleware, declaring routes, and even extending the original framework.
The route defined by the BFF function will be registered after the route defined by the app.ts
file, so here you can also intercept the route defined by the BFF function, preprocess or respond in advance.
The Koa framework is written in a similar way to Express. It supports defining the startup logic of API Server in app.[tj]s
, performing the initialization work of the application, adding global middleware, declaring routes, extending the original framework, etc.
The route defined by the BFF function will be registered after the route defined by the app.ts
file, so here you can also intercept the route defined by the BFF function, preprocess or respond in advance.
Use the framework writing, when there is no app.ts
, Modern.js will add koa-body by default. When there is app.ts
, if the developer wants to use the BFF function with Body, he needs to ensure that the koa-body middleware has been added.