等待一个插件完成注册,然后再继续注册下一个插件

Pub*_*cus 5 node.js fastify

我如何等待一个插件完成注册,然后再继续注册下一个插件?

.env我希望使用使用插件从文件中检索到的凭据来初始化与数据库的连接fastify-env

Fastify在加载环境变量之前继续注册fastify-sequelize插件。这会导致错误。TypeError: Cannot read property 'DB_NAME' of undefined

'use strict'

const path = require('path')
const AutoLoad = require('fastify-autoload')
const fastifyEnv = require('fastify-env')
const fsequelize = require('fastify-sequelize')

module.exports = function (fastify, opts, next) {
  fastify
    .register(fastifyEnv, {
      schema: {
        type: 'object',
        required: [ 'PORT', 'NODE_ENV', 'DB_NAME', 'DB_USERNAME', 'DB_PASSWORD' ],
        properties: {
          PORT: { type: 'integer' },
          NODE_ENV: { type: 'string' },
          DB_NAME: { type: 'string' },
          DB_USERNAME: { type: 'string' },
          DB_PASSWORD: { type: 'string' }
        }
      },
      dotenv: true
    }).ready((err) => {
      if (err) console.error(err)
      console.log("config ready=",fastify.config) // This works!
    })

  fastify.register(fsequelize, {
      instance: 'sequelize',
      autoConnect: true,
      dialect: 'postgres',
      database: fastify.config.DB_NAME,
      username: fastify.config.DB_USERNAME,
      password: fastify.config.DB_PASSWORD
  })
  fastify.register(AutoLoad, {
    dir: path.join(__dirname, 'plugins'),
    options: Object.assign({}, opts)
  })

  fastify.register(AutoLoad, {
    dir: path.join(__dirname, 'services'),
    options: Object.assign({}, opts)
  })


  next()
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*kes 1

Fastify 以相同的方式注册插件和中间件,同步且按照注册的顺序依次注册。它不应该异步地需要这些模块。

但是,您可以为每个插件使用许多不同的前后处理程序。

https://github.com/fastify/fastify/blob/master/docs/Lifecycle.md