繁体   English   中英

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

[英]Wait for one plugin to finish registering, before proceeding to register the next one

在继续注册下一个插件之前,我该如何等待一个插件完成注册?

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

在加载环境变量之前, Fastify继续注册fastify-sequelize -plugin。 这导致错误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()
}

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

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

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

你的脚本应该工作,我认为问题是由其他东西引起的。

反正你可以使用.after后API .register

const Fastify = require('fastify')
const fastify = Fastify({ logger: false })

fastify.register((instance, opts, next) => {
  console.log('one')
  setTimeout(next, 1000)
}).after(() => {
  fastify.register((instance, opts, next) => {
    console.log('two')
    setTimeout(next, 1000)
  })
  fastify.register((instance, opts, next) => {
    console.log('three')
    next()
  })
})

fastify.register((instance, opts, next) => {
  console.log('four')
  next()
})

fastify.listen(3000)

将打印:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM