插件

Fastify 允许用户使用插件扩展其功能。

一个插件可以是一组路由,一个服务器装饰器等,可以使用 register 函数注册插件。

默认情况下,register 创建了一个新的作用域,这意味着如果对 Fastify 实例(通过 decorate)进行一些更改,则此更改不会反映到当前上下文的祖先中,而只会反映到其子节点。这个特性允许我们实现插件封装和继承,这样就创建了一个直接非循环图(DAG),就不会有交叉依赖关系引起的问题。

使用方法:

fastify.register(plugin, [options])

Example:

fastify.register([
  require('./another-route'),
  require('./yet-another-route')
], opts)

错误处理

错误处理由 avvio 实现。
一般来说,强烈建议你处 register 回调中的错误, 否则服务器将无法启动,你将在 listen 回调中找到未处理的错误。

创建一个插件

创建插件非常简单,你只要创建一个包含三个参数的方法。第一个是 fastify 实例,第二个是一个配置对象,最后一个是 next 回调。
Example:

module.exports = function (fastify, opts, next) {
  fastify.decorate('utility', () => {})

  fastify.get('/', handler)

  next()
}

register 中使用其他 register:

module.exports = function (fastify, opts, next) {
  fastify.decorate('utility', () => {})

  fastify.get('/', handler)

  fastify.register(require('./other-plugin'))

  next()
}

处理作用域

如果使用注册插件仅仅是为了使用 decorate 扩展 server 的功能,那么应该告诉 Fastify 不要创建一个新的作用域,否则

所做的更改将无法在上级作用域内访问。

有两种方法告诉 Fastify 不要创建一个新的作用域:

建议使用 fastify-plugin 模块,可以传递一个表示 Fastify 的版本范围的参数作为插件将支持的 Fastify 版本。

const fp = require('fastify-plugin')

module.exports = fp(function (fastify, opts, next) {
  fastify.decorate('utility', () => {})
  next()
}, '0.x')

查看 fastify-plugin 文档。

如果不使用 fastify-plugin 模块, 可以使用 'skip-override' 隐藏属性,但是 fastify 不建议这样,因为如果将来Fastify API发生变化,那么你将负责更新该模块,而如果使用 fastify-plugin,则可以确保向后兼容。

function yourPlugin (fastify, opts, next) {
  fastify.decorate('utility', () => {})
  next()
}
yourPlugin[Symbol.for('skip-override')] = true
module.exports = yourPlugin

results matching ""

    No results matching ""