title:

建议开发者使用 egg-init --type=simple showcase 来生成并观察推荐的项目结构和配置。

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. };

修改为:

  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;

同时,框架开发者需要改变写法如下,否则应用开发者自定义 Service 等基类会有问题:

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

Private property && Lazy Initialization

  • 私有属性用 Symbol 来挂载。
  • Symbol 的描述遵循 jsdoc 的规则,描述映射后的类名+属性名。
  • 延迟初始化。
  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. }