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()
}