EggBornJS adds a Startup mechanism to allow initialization when system start

The development mechanism of Startup is similar to Schedule

Declaration of Startup

src/module/test-party/backend/src/config/config.js

module.exports = appInfo => {
  const config = {};

  // startups
  config.startups = {
    startupAll: {
      type: 'worker',
      path: 'test/feat/startup/all',
    },
    startupInstance: {
      type: 'worker',
      instance: true,
      path: 'test/feat/startup/instance',
    },
  };  

  return config;
};
Name Description
type all, worker
path API Route to be performed
instance Whether to inject instance object into the context when the API Route performed

What is the nature of attribute instance?

  • We mentioned earlier that EggBornJS supports multiple instances. Because Startup is triggered by the system, there is no instance information in the context
  • If instance set to false, the API Route needs to handle the logic related to multiple instances by itself
  • If instance set to true, the system will automatically loop multiple instances, perform API Route in turn, and inject instance object into the context environment, thus simplifying the development workload of API Route

Declaration of API Route

src/module/test-party/backend/src/routes.js

// test/feat/startup
{ method: 'post', path: 'test/feat/startup/all', controller: testFeatStartup, middlewares: 'inner', meta: { instance: { enable: false } } },
{ method: 'post', path: 'test/feat/startup/instance', controller: testFeatStartup, middlewares: 'inner', meta: { auth: { enable: false } } },

Name Description
middlewares Specify the middleware inner, only allowed performed inner access
instance.enable Disable the middleware instance
auth.enable Disable the middleware auth

Why disable the global middleware auth?

  • Because Startup is triggered by the system, there is no user information in its context

Controller Action

src/module/test-party/backend/src/controller/test/feat/startup.js

const require3 = require('require3');
const assert = require3('assert');

module.exports = app => {

  class StartupController extends app.Controller {

    async all() {
      console.log('test/feat/startup: all');
      assert.equal(this.ctx.instance, undefined);
      this.ctx.success();
    }

    async instance() {
      console.log(`test/feat/startup: instance:${this.ctx.instance.id}`);
      assert(this.ctx.instance.id > 0);
      this.ctx.success();
    }

  }

  return StartupController;
};