egg.js使用笔记

基础功能

中间件(Middleware)

我们介绍了 Egg 是基于 Koa 实现的,所以 Egg 的中间件形式和 Koa 的中间件形式是一样的,都是基于洋葱圈模型。每次我们编写一个中间件,就相当于在洋葱外面包了一层。

我们约定一个中间件是一个放置在 app/middleware 目录下的单独文件,它需要 exports 一个普通的 function,接受两个参数:

  • options: 中间件的配置项,框架会将 app.config[${middlewareName}] 传递进来。
  • app: 当前应用 Application 的实例。

在框架中,一个完整的中间件是包含了配置处理的。

编写中间件

我们先来通过编写一个简单的 gzip 中间件,来看看中间件的写法。

// app/middleware/gzip.js
const isJSON = require('koa-is-json');
const zlib = require('zlib');

async function gzip(ctx, next) {
    
    
  await next();

  // 后续中间件执行完成后将响应体转换成 gzip
  let body = ctx.body;
  if (!body) return;
  if (isJSON(body)) body = JSON.stringify(body);

  // 设置 gzip body,修正响应头
  const stream = zlib.createGzip();
  stream.end(body);
  ctx.body = stream;
  ctx.set('Content-Encoding', 'gzip');
}

可以看到,框架的中间件和 Koa 的中间件写法是一模一样的,所以任何 Koa 的中间件都可以直接被框架使用。

插件

插件机制是我们框架的一大特色。它不但可以保证框架核心的足够精简、稳定、高效,还可以促进业务逻辑的复用,生态圈的形成。有人可能会问了

  • Koa 已经有了中间件的机制,为啥还要插件呢?
  • 中间件、插件、应用它们之间是什么关系,有什么区别?
  • 我该怎么使用一个插件?
  • 如何编写一个插件?

接下来我们就来逐一讨论:

为什么要用插件?

我们在使用 Koa 中间件过程中发现了下面一些问题:

  1. 中间件加载其实是有先后顺序的,但是中间件自身却无法管理这种顺序,只能交给使用者。这样其实非常不友好,一旦顺序不对,结果可能有天壤之别。
  2. 中间件的定位是拦截用户请求,并在它前后做一些事情,例如:鉴权、安全检查、访问日志等等。但实际情况是,有些功能是和请求无关的,例如:定时任务、消息订阅、后台逻辑等等。
  3. 有些功能包含非常复杂的初始化逻辑,需要在应用启动的时候完成。这显然也不适合放到中间件中去实现。

综上所述,我们需要一套更加强大的机制,来管理、编排那些相对独立的业务逻辑。

中间件、插件、应用的关系

一个插件其实就是一个『迷你的应用』,和应用(app)几乎一样:

  • 它包含了 Service、中间件、配置、框架扩展等等。
  • 它没有独立的 Router 和 Controller。
  • 它没有 plugin.js,只能声明跟其他插件的依赖,而不能决定其他插件的开启与否。

他们的关系是:

  • 应用可以直接引入 Koa 的中间件。
  • 当遇到上一节提到的场景时,则应用需引入插件。
  • 插件本身可以包含中间件。
  • 多个插件可以包装为一个上层框架。

路由

Router主要处理请求URL和具体承担执行动作的Controller之间的对应关系,框架约定了 app/router.js 文件(CommonJS规范文件)用于统一所有路由规则。

通过统一的配置,我们可以避免路由规则逻辑散落在多个地方,从而出现未知的冲突,集中在一起我们可以更方便的来查看全局的路由规则。

如何定义Router

在app/router.js中定义URL和Controller映射关系:

// app/router.js
module.exports = app => {
    
    
  const {
    
     router, controller } = app;
  router.get('/user/:id', controller.user.info);
};

在app/controller 目录下面实现 Controller:

// app/controller/user.js
class UserController extends Controller {
    
    
  async info() {
    
    
    const {
    
     ctx } = this;
    ctx.body = {
    
    
      name: `hello ${
      
      ctx.params.id}`,
    };
  }
}

这样就完成了一个最简单的 Router 定义,当用户执行 GET /user/123,user.js 这个里面的 info 方法就会执行。

Router 详细定义说明

下面是路由的完整定义,参数可以根据场景的不同,自由选择:

router.verb('path-match', app.controller.action);
router.verb('router-name', 'path-match', app.controller.action);
router.verb('path-match', middleware1, ..., middlewareN, app.controller.action);
router.verb('router-name', 'path-match', middleware1, ..., middlewareN, app.controller.action);

路由完整定义主要包括5个主要部分:

  • verb - 用户触发动作,支持 get,post 等所有 HTTP 方法,后面会通过示例详细说明。
    • router.head - HEAD
    • router.options - OPTIONS
    • router.get - GET
    • router.put - PUT
    • router.post - POST
    • router.patch - PATCH
    • router.delete - DELETE
    • router.del - 由于 delete 是一个保留字,所以提供了一个 delete 方法的别名。
    • router.redirect - 可以对 URL 进行重定向处理,比如我们最经常使用的可以把用户访问的根目录路由到某个主页。
  • router-name 给路由设定一个别名,可以通过 Helper 提供的辅助函数 pathFor 和 urlFor 来生成 URL。(可选)
  • path-match - 路由 URL 路径。
  • middleware1 - 在 Router 里面可以配置多个 Middleware。(可选)
  • controller - 指定路由映射到的具体的 controller 上,controller 可以有两种写法:
    • app.controller.user.fetch - 直接指定一个具体的 controller
    • ‘user.fetch’ - 可以简写为字符串形式

注意事项

  1. 在 Router 定义中, 可以支持多个 Middleware 串联执行
  2. Controller 必须定义在 app/controller 目录中。
  3. 一个文件里面也可以包含多个 Controller 定义,在定义路由的时候,可以通过 f i l e N a m e . {fileName}. fileName.{functionName} 的方式指定对应的 Controller。
  4. Controller 支持子目录,在定义路由的时候,可以通过 d i r e c t o r y N a m e . {directoryName}. directoryName.{fileName}.${functionName} 的方式制定对应的 Controller。

RESTful 风格的 URL 定义

如果想通过 RESTful 的方式来定义路由, 我们提供了 app.router.resources(‘routerName’, ‘pathMatch’, controller) 快速在一个路径上生成 CRUD 路由结构。

**// app/router.js
module.exports = app => {
    
    
  const {
    
     router, controller } = app;
  router.resources('posts', '/api/posts', controller.posts);
  router.resources('users', '/api/v1/users', controller.v1.users); // app/controller/v1/users.js
};**

上面代码就在 /posts 路径上部署了一组 CRUD 路径结构,对应的 Controller 为 app/controller/posts.js 接下来, 你只需要在 posts.js 里面实现对应的函数就可以了。

// app/controller/posts.js
exports.index = async () => {
    
    };

exports.new = async () => {
    
    };

exports.create = async () => {
    
    };

exports.show = async () => {
    
    };

exports.edit = async () => {
    
    };

exports.update = async () => {
    
    };

exports.destroy = async () => {
    
    };

如果我们不需要其中的某几个方法,可以不用在 posts.js 里面实现,这样对应 URL 路径也不会注册到 Router。

router 实战

controller怎么获取参数

  1. Query String 方式
// app/controller/search.js
exports.index = async ctx => {
    
    
  ctx.body = `search: ${
      
      ctx.query.name}`;
};
  1. 参数命名方式
// app/controller/user.js
exports.info = async ctx => {
    
    
  ctx.body = `user: ${
      
      ctx.params.id}, ${
      
      ctx.params.name}`;
};
  1. 复杂参数的获取
    路由里面也支持定义正则,可以更加灵活的获取参数:
// app/router.js
module.exports = app => {
    
    
  app.router.get(/^\/package\/([\w-.]+\/[\w-.]+)$/, app.controller.package.detail);
};

// app/controller/package.js
exports.detail = async ctx => {
    
    
  // 如果请求 URL 被正则匹配, 可以按照捕获分组的顺序,从 ctx.params 中获取。
  // 按照下面的用户请求,`ctx.params[0]` 的 内容就是 `egg/1.0.0`
  ctx.body = `package:${
      
      ctx.params[0]}`;
};

// curl http://127.0.0.1:7001/package/egg/1.0.0

表单内容获取

一般是post类型的请求:

// app/router.js
module.exports = app => {
    
    
  app.router.post('/form', app.controller.form.post);
};

// app/controller/form.js
exports.post = async ctx => {
    
    
  ctx.body = `body: ${
      
      JSON.stringify(ctx.request.body)}`;
};
// 模拟发起 post 请求。
// curl -X POST http://127.0.0.1:7001/form --data '{"name":"controller"}' --header 'Content-Type:application/json'

这里直接发起 POST 请求会报错:‘secret is missing’。错误信息来自 koa-csrf/index.js#L69 。

原因:框架内部针对表单 POST 请求均会验证 CSRF 的值,因此我们在表单提交时,请带上 CSRF key 进行提交,可参考安全威胁csrf的防范

注意:上面的校验是因为框架中内置了安全插件 egg-security,提供了一些默认的安全实践,并且框架的安全插件是默认开启的,如果需要关闭其中一些安全防范,直接设置该项的 enable 属性为 false 即可。

「除非清楚的确认后果,否则不建议擅自关闭安全插件提供的功能。」

这里在写例子的话可临时在 config/config.default.js 中设置

exports.security = {
    
    
  csrf: false
};

表单校验

// app/controller/user.js
const createRule = {
    
    
  username: {
    
    
    type: 'email',
  },
  password: {
    
    
    type: 'password',
    compare: 're-password',
  },
};

exports.create = async ctx => {
    
    
  // 如果校验报错,会抛出异常
  ctx.validate(createRule);
  ctx.body = ctx.request.body;
};
// curl -X POST http://127.0.0.1:7001/user --data '[email protected]&password=111111&re-password=111111'

重定向

内部重定向

处理controller重定向:

// app/router.js
module.exports = app => {
    
    
  app.router.get('index', '/home/index', app.controller.home.index);
  app.router.redirect('/', '/home/index', 302);
};

// app/controller/home.js
exports.index = async ctx => {
    
    
  ctx.body = 'hello controller';
};

// curl -L http://localhost:7001
外部重定向

请求url重定向:

// app/router.js
module.exports = app => {
    
    
  app.router.get('/search', app.controller.search.index);
};

// app/controller/search.js
exports.index = async ctx => {
    
    
  const type = ctx.query.type;
  const q = ctx.query.q || 'nodejs';

  if (type === 'bing') {
    
    
    ctx.redirect(`http://cn.bing.com/search?q=${
      
      q}`);
  } else {
    
    
    ctx.redirect(`https://www.google.co.kr/search?q=${
      
      q}`);
  }
};

// curl http://localhost:7001/search?type=bing&q=node.js
// curl http://localhost:7001/search?q=node.js

中间件的使用

如果我们想把用户某一类请求的参数都大写,可以通过中间件来实现。 这里我们只是简单说明下如何使用中间件,更多请查看 中间件

// app/controller/search.js
exports.index = async ctx => {
    
    
  ctx.body = `search: ${
      
      ctx.query.name}`;
};

// app/middleware/uppercase.js
module.exports = () => {
    
    
  return async function uppercase(ctx, next) {
    
    
    ctx.query.name = ctx.query.name && ctx.query.name.toUpperCase();
    await next();
  };
};

// app/router.js
module.exports = app => {
    
    
  app.router.get('s', '/search', app.middleware.uppercase(), app.controller.search)
};

// curl http://localhost:7001/search?name=egg

单个文件太多路由映射?

如上所述,我们并不建议把路由规则逻辑散落在多个地方,会给排查问题带来困扰。

若确实有需求,可以如下拆分:

// app/router.js
module.exports = app => {
    
    
  require('./router/news')(app);
  require('./router/admin')(app);
};

// app/router/news.js
module.exports = app => {
    
    
  app.router.get('/news/list', app.controller.news.list);
  app.router.get('/news/detail', app.controller.news.detail);
};

// app/router/admin.js
module.exports = app => {
    
    
  app.router.get('/admin/user', app.controller.admin.user);
  app.router.get('/admin/log', app.controller.admin.log);
};

也可直接使用 egg-router-plus

控制器(Controller)

我们通过 Router 将用户的请求基于 method 和 URL 分发到了对应的 Controller 上,那 Controller 负责做什么?

简单的说 Controller 负责解析用户的输入,处理后返回相应的结果,例如

  1. 在 RESTful 接口中,Controller 接受用户的参数,从数据库中查找内容返回给用户或者将用户的请求更新到数据库中。
  2. 在 HTML 页面请求中,Controller 根据用户访问不同的 URL,渲染不同的模板得到 HTML 返回给用户。
  3. 在代理服务器中,Controller 将用户的请求转发到其他服务器上,并将其他服务器的处理结果返回给用户。

框架推荐 Controller 层主要对用户的请求参数进行处理(校验、转换),然后调用对应的 service 方法处理业务,得到业务结果后封装并返回:
4. 获取用户通过 HTTP 传递过来的请求参数。
5. 校验、组装参数。
6. 调用 Service 进行业务处理,必要时处理转换 Service 的返回结果,让它适应用户的需求。
7. 通过 HTTP 将结果响应给用户。

如何编写controller

所有的 Controller 文件都必须放在 app/controller 目录下,可以支持多级目录,访问的时候可以通过目录名级联访问。Controller 支持多种形式进行编写,可以根据不同的项目场景和开发习惯来选择。

服务(service)

简单来说,Service 就是在复杂业务场景下用于做业务逻辑封装的一个抽象层,提供这个抽象有以下几个好处:

保持 Controller 中的逻辑更加简洁。
保持业务逻辑的独立性,抽象出来的 Service 可以被多个 Controller 重复调用。
将逻辑和展现分离,更容易编写测试用例,测试用例的编写具体可以查看这里。

使用场景

复杂数据的处理,比如要展现的信息需要从数据库获取,还要经过一定的规则计算,才能返回用户显示。或者计算完成后,更新到数据库。
第三方服务的调用,比如 GitHub 信息获取等。

定义 Service

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

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;

猜你喜欢

转载自blog.csdn.net/u010682774/article/details/111415632