Application Startup Configuration

When the application starts up, we often need to set up some initialization logic. The application bootstraps with those specific configurations. It is in a healthy state and be able to take external service requests after those configurations successfully applied. Otherwise, it failed.

The framework starts with a file called app.js that executes the application initialization logic, if present, and it returns a function.

For example, we need to load a list of national cities from the remote server during application startup for subsequent use in the controller:

  1. // app.js
  2. module.exports = app => {
  3. app.beforeStart(async () => {
  4. // The lifecycle method runs before the application bootstraps
  5. app.cities = await app.curl('http://example.com/city.json', {
  6. method: 'GET',
  7. dataType: 'json',
  8. });
  9. // also could create an anonymous context to call Service
  10. // const ctx = app.createAnonymousContext();
  11. // app.cities = await ctx.service.cities.load();
  12. });
  13. };

cities attribute has attached on the global app. It can be accessed in the controller,

  1. // app/controller/home.js
  2. class HomeController extends Controller {
  3. async index() {
  4. // now you can use `ctx.app.cities`
  5. }
  6. }

Note: When the framework executes the lifecycle method beforeStart, do not run time-consuming operation. The framework enables a Timeout setting by default when it starts up.