服务Server
定义service
// app/service/user.js
const Service = require('egg').Service
class UserService extends Service {
async find (uid) {
const user = await this.ctx.mysql.query('SELECT * FROM user WHERE uid=?', uid);
return user;
}
}
module.exports = UserService;
// 每次用户请求,都会实例化对应Service,继承于egg.Service,提供属性便利开发
· this.ctx: 当前请求的上下文Context对象的实例,处理当前请求的各种属性和方法
· this.app: 当前应用Application对象的实例,获取框架提供的全局对象和方法
· this.service: 应用定义的Service,可以访问到抽象出的业务层,等价于this.ctx.service
· this.config: 应用运行时的配置项
· this.logger: logger对象,对象上有四个方法(debug, info, warn, error)分别代表打印不同级别的日志
Service ctx 详解
可以直接通过this.ctx获取上下文相关信息,拿到框架给我们封装的各种便捷属性
· this.ctx.curl 发起网络请求
· this.ctx.service.otherService 调用其他的Service
· this.ctx.db 发起数据库调用等等
注意事项
· Service文件必须放在app/service目录,可以支持多级目录。访问的时候通过目录名级联访问
· 一个Service文件只能包含一个类,这个类需要通过module.exports的方式返回
· Service需要通过class的方式定义,父类必须是egg.Service
· Service不是单例,是请求级别的对象,框架每次请求首次访问ctx.service.xx时会延迟实例化,
所以Service可以通过this.ctx获取到当前的上下文
Service的使用
// app/router.js
module.exports = app => {
app.router.get('/user/:id', app.controller.user.info);
};
// app/controller/user.js
const Controller = require('egg').Controller;
class UserController extends Controller {
async info() {
const { ctx } = this;
const userId = ctx.params.id;
const userInfo = await ctx.service.user.find(userId);
ctx.body = userInfo;
}
}
module.exports = UserController;
// app/service/user.js
const Service = require('egg').Service;
class UserService extends Service {
// 默认不需要提供构造函数。
// constructor(ctx) {
// super(ctx); 如果需要在构造函数做一些处理,一定要有这句话,才能保证后面 `this.ctx`的使用。
// // 就可以直接通过 this.ctx 获取 ctx 了
// // 还可以直接通过 this.app 获取 app 了
// }
async find(uid) {
// 假如 我们拿到用户 id 从数据库获取用户详细信息
const user = await this.ctx.db.query('select * from user where uid = ?', uid);
// 假定这里还有一些复杂的计算,然后返回需要的信息。
const picture = await this.getPicture(uid);
return {
name: user.user_name,
age: user.age,
picture,
};
}
async getPicture(uid) {
const result = await this.ctx.curl(`http://photoserver/uid=${uid}`, { dataType: 'json' });
return result.data;
}
}
module.exports = UserService;
// curl http://127.0.0.1:7001/user/1234