Eggjs 学习笔记 02

Service 层

如果把 Controller 层看作是与客户端交互并接收请求数据然后返回数据的作用,那么 Service 层则是处理数据、查询数据(包括数据库的查询,第三方服务的调用)、
或者是计算数据的抽象层,使得展现和逻辑分离。
定义一个 Service
位置:app/service/userservice.js

const {Service} = require('egg')

class UserService extends Service {
  async find(uid) {
    const user = await this.ctx.db.query(
      'select * from user where uid = ?',
      uid,                
    );
    return user;
  }

}

module.exports = UserService;

属性
Service 和 Controller 在属性方面相似,有如下属性

  • this.ctx 上下文对象的实例 Context
  • this.app 当前应用Application对象的实例,通过它我们可以拿到框架提供的全局对象和方法
  • this.service 应用定义的 Service,通过它我们可以访问到其他业务层,等价于 this.ctx.service
  • this.config 应用运行时的配置项
  • this.logger logger对象,上面有四个方法 (debug, info, warn, error),分别代表打印四个不同级别的日志

    使用 Service 
    // app/router.js
    module.exports = (app) => {
      app.router.get('/user/:id', app.controller.user.info);
    }
    
    // app/controller/user.js
    const {Controller} = require('egg');
    class UserController extends Controller {
      async info() {
        const {ctx} = this;
        const userId = ctx.params.id; // 从路由上获取参数
        // 调用Service 查询用户信息
        const userInfo = await ctx.service.user.find(userId); 
        ctx.body = userInfo;
      }
    }
    
    module.exports = UserController;
    
    // app/service/user.js
    const {Service} require('egg');
    class UserService extends Service {
      // 从数据库查询数据
      async find(uid) {
        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) {
    // 使用 this.ctx.curl 发起网络调用 const result
    = await this.ctx.curl(`http://photoserver/uid=${uid}`, {dataType: 'json'} ); return result.data; } } module.exports = UserService

     

posted on 2023-03-18 09:25  Deflect-o-Bot  阅读(32)  评论(0编辑  收藏  举报