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:

  1. 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
  2. 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

event: {
  declarations: {
    loginInfo: 'Login Info',
  },
},
Name Description
loginInfo event name
Login Info event description

2. Raise Event

a-base-sync/backend/src/controller/auth.js

async getLoginInfo() {
  const info = {
    user: this.ctx.user,
    instance: this.getInstance(),
    config: this.getConfig(),
  };
  // login info event
  await this.ctx.meta.event.invoke({
    name: 'loginInfo', data: { info },
  });
  return info;
}
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

event: {
  implementations: {
    'a-base:loginInfo': 'test/event/loginInfo',
  },
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

{ 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

async loginInfo() {
  // change the config of mobile layout by checking the user's login status
  const data = this.ctx.request.body.data;
  const info = data.info;
  const provider = info.user && info.user.provider;
  if (provider && provider.module === 'a-authgithub' && provider.providerName === 'authgithub') {
    info.config = extend(true, info.config, {
      modules: {
        'a-layoutmobile': {
          layout: {
            login: '/a/login/login',
            loginOnStart: true,
            toolbar: {
              tabbar: true, labels: true, bottomMd: true,
            },
            tabs: [
              { name: 'Mine', tabLinkActive: true, iconMaterial: 'person', url: '/a/user/user/mine' },
            ],
          },
        },
      },
    });
  }
  this.ctx.success();
}