diff --git a/docs/Plugins-Guide.md b/docs/Plugins-Guide.md index 5849152..ea6ef8a 100644 --- a/docs/Plugins-Guide.md +++ b/docs/Plugins-Guide.md @@ -271,6 +271,28 @@ module.exports = fp(dbPlugin) ``` 你还可以告诉 `fastify-plugin` 去检查安装的 Fastify 版本, 万一你需要特定的 api. +正如前面所述,Fastify 在 `.listen()`、`.inject()` 以及 `.ready()` 被调用,也即插件被声明 __之后__ 才开始加载插件。这么一来,即使插件通过 [`decorate`](https://github.com/fastify/docs-chinese/blob/master/docs/Decorators.md) 向外部的 fastify 实例注入了变量,在调用 `.listen()`、`.inject()` 和 `.ready()` 之前,这些变量是获取不到的。 + +当你需要在 `register` 方法的 `options` 参数里使用另一个插件注入的变量时,你可以向 `options` 传递一个函数参数,而不是对象: +```js +const fastify = require('fastify')() +const fp = require('fastify-plugin') +const dbClient = require('db-client') + +function dbPlugin (fastify, opts, next) { + dbClient.connect(opts.url, (err, conn) => { + fastify.decorate('db', conn) + next() + }) +} + +fastify.register(fp(dbPlugin), { url: 'https://example.com' }) +fastify.register(require('your-plugin'), parent => { + return { connection: parent.db, otherOption: 'foo-bar' } +}) +``` +在上面的例子中,`register` 方法的第二个参数的 `parent` 变量是注册了插件的**外部 fastify 实例**的一份拷贝。这就意味着我们可以获取到之前声明的插件所注入的变量了。 + ## 错误处理 你的插件也可能在启动的时候失败. 或许你预料到这个并且在这种情况下有特定的处理逻辑. 你该怎么实现呢? diff --git a/docs/Plugins.md b/docs/Plugins.md index d05e5aa..0351948 100644 --- a/docs/Plugins.md +++ b/docs/Plugins.md @@ -40,6 +40,25 @@ fastify.register(require('fastify-foo'), { }) ``` +`options` 参数还可以是一个在插件注册时确定的 `函数`,这个函数的第一位参数是 fastify 实例: + +```js +const fp = require('fastify-plugin') + +fastify.register(fp((fastify, opts, next) => { + fastify.decorate('foo_bar', { hello: 'world' }) + + next() +})) + +// fastify-foo 的 options 参数会是 { hello: 'world' } +fastify.register(require('fastify-foo'), parent => parent.foo_bar) +``` + +传给函数的 fastify 实例是插件声明时**外部 fastify 实例**的最新状态,允许你访问**注册顺序**在前的插件通过 [`decorate`](https://github.com/fastify/docs-chinese/blob/master/docs/Decorators.md) 注入的变量。这在需要依赖前置插件对于 Fastify 实例的改动时派得上用场,比如,使用已存在的数据库连接来包装你的插件。 + +请记住,传给函数的 fastify 实例和传给插件的实例是一样的,不是外部 fastify 实例的引用,而是拷贝。任何对函数的实例参数的操作结果,都会和在插件函数中操作的结果一致。也就是说,如果调用了 `decorate`,被注入的变量在插件函数中也是可用的,除非你使用 [`fastify-plugin`](https://github.com/fastify/fastify-plugin) 包装了这个插件。 + #### 路由前缀选项 如果你传入以 `prefix`为 key , `string` 为值的选项, Fastify 会自动为这个插件下所有的路由添加这个前缀, 更多信息可以查询 [这里](https://github.com/fastify/docs-chinese/blob/master/docs/Routes.md#route-prefixing).