Egg.js 控制器基類 BaseController
-
按照類的方式編寫 Controller,不僅可以讓我們更好的對 Controller 層代碼進行抽象
-
例如將一些統一的處理抽象成一些私有方法,還可以通過自定義 Controller 基類的方式封裝應用中常用的方法
-
官方要求在app/core中配置核心方法
// app/core/base.js const { Controller } = require('egg'); class BaseController extends Controller { get user() { return this.ctx.session.user; } success(data) { this.ctx.body = { success: true data }; } notFound(msg) { msg = msg || 'not found'; this.ctx.throw(404, msg); } } module.exports = BaseController; // 繼承core/base const BaseController = require('../core/base'); class PostController extends BaseController { async list() { const posts = await this.service.listByUser(this.user); this.success(posts); } } module.exports = PostController;
Egg.js 控制器兼容寫法
官方不推薦使用,只是爲了兼容
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
// 這裏講context對象通過參數的形式傳遞過來
// 推薦的寫法是:const { ctx } = this; 或者 this.ctx
async index(ctx) {
await ctx.render('home');
}
}
module.exports = HomeController;