关于egg.js里service的最佳实践,是否可以在service里处理请求参数?
发布于 4 年前 作者 elicip 4329 次浏览 来自 问答

看egg.js的官方文档里,指出controller是负责处理用户请求的参数的,然后传递到service里进行后续处理。我想问下,在service里直接通过获取ctx.query或者ctx.params进行处理合适吗? 比如:我需要获取一个列表数据,我写一个getList的service,同时这个列表数据支持排序,所以我应该直接在service里获取order_by的值,还是现在controller里获取再传递给service比较好?

在controller里获取query参数

// app/controller/user.js
const Controller = require('egg').Controller;
class UserController extends Controller {
  async index() {
    const { ctx } = this;
    const orderBy = ctx.query.order_by;
    const userList = await ctx.service.user.getList(orderBy);
    ctx.body = userList;
  }
}
module.exports = UserController;

// app/service/user.js
const Service = require('egg').Service;

class UserService extends Service {
  async getList(order) {
    const users = await this.ctx.db.query('select * from user order by ', order);
    return user;
  }
}
module.exports = UserService;

PK

在service里获取query参数

// app/controller/user.js
const Controller = require('egg').Controller;
class UserController extends Controller {
  async index() {
    const { ctx } = this;
    const userList = await ctx.service.user.getList();
    ctx.body = userList;
  }
}
module.exports = UserController;

// app/service/user.js
const Service = require('egg').Service;

class UserService extends Service {
  async getList() {
  	const order = this.ctx.query.order_by;
    const users = await this.ctx.db.query('select * from user order by ', order);
    return user;
  }
}
module.exports = UserService;
3 回复

建议传给他,最好可以的话service不要摸到ctx.request方便方法复用

请求参数 属于 HTTP 层,跟具体的请求协议有关,在 Controller 里面消化掉。 Service 是单纯的业务逻辑。

回到顶部