2

How can I wait for one plugin to finish registering, before proceeding to register the next one?

I wish to initialize the connection to the database using credentials that are retrieved from a .env file using the plugin fastify-env.

Fastify proceeds to register the fastify-sequelize-plugin before the environment variables are loaded. This leads to the error 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()
}
4

2 回答 2

0

Fastify 以同样的方式注册插件和中间件,同步的,按照注册的顺序一个接一个。它不应该异步要求这些模块。

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

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

于 2019-07-17T20:38:09.480 回答
0

您的脚本应该可以工作,我认为问题是由其他原因引起的。

无论如何,您可以在以下内容.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)

将打印:

于 2019-08-27T16:10:28.620 回答