Title: Code Style Guide

Developers are advised to use egg-init --type=simple showcase to generate and observe the recommended project structure and configuration.

Classify

  1. // old style
  2. module.exports = app => {
  3. class UserService extends app.Service {
  4. async list() {
  5. return await this.ctx.curl('https://eggjs.org');
  6. }
  7. }
  8. return UserService;
  9. };

change to:

  1. const Service = require('egg').Service;
  2. class UserService extends Service {
  3. async list() {
  4. return await this.ctx.curl('https://eggjs.org');
  5. }
  6. }
  7. module.exports = UserService;

Additionally, the framework developer needs to change the syntax as follows, otherwise the application developer will have problems customizing base classes such as Service:

  1. const egg = require('egg');
  2. module.exports = Object.assign(egg, {
  3. Application: class MyApplication extends egg.Application {
  4. // ...
  5. }
  6. // ...
  7. });

Private properties & Lazy Initialization

  • Private properties are mounted with Symbol.
  • The description of Symbol follows the rules of jsdoc, describing the mapped class name + attribute name.
  • Delayed initialization.
  1. // app/extend/application.js
  2. const CACHE = Symbol('Application#cache');
  3. const CacheManager = require('../../lib/cache_manager');
  4. module.exports = {
  5. get cache() {
  6. if (!this[CACHE]) {
  7. this[CACHE] = new CacheManager(this);
  8. }
  9. return this[CACHE];
  10. }
  11. };