Scenario
In the actual business development, in order to further enhance the flexibility and scalability, the feature of event at backend
is provided. We can consider the following application scenarios:
- When the page is initialized, the frontend will call the backend API route
/a/base/auth/echo
to return the current user’s information. If there is no login, the login page will be opened automatically - Since this is a system architecture provided by module
a-base
, how can other business modules append data to the user information returned by this backend API route?
For Example
Take the above scenario as an example to analyze how the module a-base
raises event and how other modules respond to the event
Raise Event
1. Declaration of Event
a-base-sync/backend/src/meta.js
- 1event: {
- 2 declarations: {
- 3 loginInfo: 'Login Info',
- 4 },
- 5},
Name | Description |
---|---|
loginInfo | event name |
Login Info | event description |
2. Raise Event
a-base-sync/backend/src/controller/auth.js
- 1async getLoginInfo() {
- 2 const info = {
- 3 user: this.ctx.user,
- 4 instance: this.getInstance(),
- 5 config: this.getConfig(),
- 6 };
- 7 // login info event
- 8 await this.ctx.meta.event.invoke({
- 9 name: 'loginInfo', data: { info },
- 10 });
- 11 return info;
- 12}
Name | Description |
---|---|
module | event module name |
name | event name |
data | event data |
Respond to Event
1. Declaration of Implementations
test-party/backend/src/meta.js
- 1event: {
- 2 implementations: {
- 3 'a-base:loginInfo': 'test/event/loginInfo',
- 4 },
Name | Description |
---|---|
a-base:loginInfo | module name:event name |
test/event/loginInfo | the API route for responding to the event |
2. Definition of API Route
test-party/backend/src/routes.js
- 1{ method: 'post', path: 'test/event/loginInfo', controller: testEventUserVerify, middlewares: 'test', meta: { auth: { enable: false } } },
3. Controller Action
In this example, respond to the event a-base:loginInfo
to determine the login way of the current user. If you log in through GitHub, modify the frontend config of the module a-layoutmobile
so as to change the page layout in the mobile scenario
test-party/backend/src/controller/test/event/userVerify.js
- 1async loginInfo() {
- 2 // change the config of mobile layout by checking the user's login status
- 3 const data = this.ctx.request.body.data;
- 4 const info = data.info;
- 5 const provider = info.user && info.user.provider;
- 6 if (provider && provider.module === 'a-authgithub' && provider.providerName === 'authgithub') {
- 7 info.config = extend(true, info.config, {
- 8 modules: {
- 9 'a-layoutmobile': {
- 10 layout: {
- 11 login: '/a/login/login',
- 12 loginOnStart: true,
- 13 toolbar: {
- 14 tabbar: true, labels: true, bottomMd: true,
- 15 },
- 16 tabs: [
- 17 { name: 'Mine', tabLinkActive: true, iconMaterial: 'person', url: '/a/user/user/mine' },
- 18 ],
- 19 },
- 20 },
- 21 },
- 22 });
- 23 }
- 24 this.ctx.success();
- 25}
Comments: