diff --git a/packages/strapi-connector-mongoose/lib/index.js b/packages/strapi-connector-mongoose/lib/index.js index b8ea8ecfe0..79fc6c1a5e 100644 --- a/packages/strapi-connector-mongoose/lib/index.js +++ b/packages/strapi-connector-mongoose/lib/index.js @@ -47,110 +47,111 @@ const createConnectionURL = opts => { }; module.exports = function(strapi) { + const { connections } = strapi.config; + const mongooseConnections = Object.keys(connections).filter(key => + isMongooseConnection(connections[key]) + ); + function initialize() { - const { connections } = strapi.config; + const connectionsPromises = mongooseConnections.map(async connectionName => { + const connection = connections[connectionName]; + const instance = new Mongoose(); - const connectionsPromises = Object.keys(connections) - .filter(key => isMongooseConnection(connections[key])) - .map(async connectionName => { - const connection = connections[connectionName]; - const instance = new Mongoose(); + _.defaults(connection.settings, strapi.config.hook.settings.mongoose); - _.defaults(connection.settings, strapi.config.hook.settings.mongoose); + const { + uri, + host, + port, + username, + password, + database, + srv, + useUnifiedTopology, + } = connection.settings; - const { - uri, + // eslint-disable-next-line node/no-deprecated-api + const uriOptions = uri ? url.parse(uri, true).query : {}; + const { authenticationDatabase, ssl, debug } = _.defaults( + connection.options, + uriOptions, + strapi.config.hook.settings.mongoose + ); + const isSrv = srv === true || srv === 'true'; + + // Connect to mongo database + const connectOptions = {}; + + if (!_.isEmpty(username)) { + connectOptions.user = username; + + if (!_.isEmpty(password)) { + connectOptions.pass = password; + } + } + + if (!_.isEmpty(authenticationDatabase)) { + connectOptions.authSource = authenticationDatabase; + } + + connectOptions.ssl = ssl === true || ssl === 'true'; + connectOptions.useNewUrlParser = true; + connectOptions.dbName = database; + connectOptions.useCreateIndex = true; + connectOptions.useUnifiedTopology = useUnifiedTopology || true; + + try { + const connectionURL = createConnectionURL({ + protocol: `mongodb${isSrv ? '+srv' : ''}`, + port: isSrv ? '' : `:${port}`, host, - port, - username, - password, - database, - srv, - useUnifiedTopology, - } = connection.settings; + auth: username ? `${username}:${encodeURIComponent(password)}@` : '', + }); - // eslint-disable-next-line node/no-deprecated-api - const uriOptions = uri ? url.parse(uri, true).query : {}; - const { authenticationDatabase, ssl, debug } = _.defaults( - connection.options, - uriOptions, - strapi.config.hook.settings.mongoose - ); - const isSrv = srv === true || srv === 'true'; + const connectionString = uri || connectionURL.toString(); - // Connect to mongo database - const connectOptions = {}; + await instance.connect(connectionString, connectOptions); + } catch (error) { + const err = new Error(`Error connecting to the Mongo database. ${error.message}`); + delete err.stack; + throw err; + } - if (!_.isEmpty(username)) { - connectOptions.user = username; + try { + const { version } = await instance.connection.db.admin().serverInfo(); + instance.mongoDBVersion = version; + } catch { + instance.mongoDBVersion = null; + } - if (!_.isEmpty(password)) { - connectOptions.pass = password; - } - } + const initFunctionPath = path.resolve( + strapi.config.appPath, + 'config', + 'functions', + 'mongoose.js' + ); - if (!_.isEmpty(authenticationDatabase)) { - connectOptions.authSource = authenticationDatabase; - } + if (fs.existsSync(initFunctionPath)) { + require(initFunctionPath)(instance, connection); + } - connectOptions.ssl = ssl === true || ssl === 'true'; - connectOptions.useNewUrlParser = true; - connectOptions.dbName = database; - connectOptions.useCreateIndex = true; - connectOptions.useUnifiedTopology = useUnifiedTopology || true; + instance.set('debug', debug === true || debug === 'true'); + instance.set('useFindAndModify', false); - try { - const connectionURL = createConnectionURL({ - protocol: `mongodb${isSrv ? '+srv' : ''}`, - port: isSrv ? '' : `:${port}`, - host, - auth: username ? `${username}:${encodeURIComponent(password)}@` : '', - }); + const ctx = { + instance, + connection, + }; - const connectionString = uri || connectionURL.toString(); + _.set(strapi, `connections.${connectionName}`, instance); - await instance.connect(connectionString, connectOptions); - } catch (error) { - const err = new Error(`Error connecting to the Mongo database. ${error.message}`); - delete err.stack; - throw err; - } - - try { - const { version } = await instance.connection.db.admin().serverInfo(); - instance.mongoDBVersion = version; - } catch { - instance.mongoDBVersion = null; - } - - const initFunctionPath = path.resolve( - strapi.config.appPath, - 'config', - 'functions', - 'mongoose.js' - ); - - if (fs.existsSync(initFunctionPath)) { - require(initFunctionPath)(instance, connection); - } - - instance.set('debug', debug === true || debug === 'true'); - instance.set('useFindAndModify', false); - - const ctx = { - instance, - connection, - }; - - _.set(strapi, `connections.${connectionName}`, instance); - - return Promise.all([ - mountComponents(connectionName, ctx), - mountApis(connectionName, ctx), - mountAdmin(connectionName, ctx), - mountPlugins(connectionName, ctx), - ]); - }); + return Promise.all([ + mountComponents(connectionName, ctx), + mountApis(connectionName, ctx), + mountAdmin(connectionName, ctx), + mountPlugins(connectionName, ctx), + ]); + }); return Promise.all(connectionsPromises); } @@ -197,10 +198,21 @@ module.exports = function(strapi) { ); } + async function destroy() { + for (const connName of mongooseConnections) { + const connection = strapi.connections[connName]; + + if (connection instanceof Mongoose) { + connection.disconnect(); + } + } + } + return { defaults, initialize, getQueryParams, + destroy, buildQuery, queries, ...relations, diff --git a/packages/strapi-connector-mongoose/lib/mount-models.js b/packages/strapi-connector-mongoose/lib/mount-models.js index 2bfd3d6cdc..0fd55a6ef6 100644 --- a/packages/strapi-connector-mongoose/lib/mount-models.js +++ b/packages/strapi-connector-mongoose/lib/mount-models.js @@ -272,9 +272,9 @@ module.exports = async ({ models, target }, ctx) => { }); }; - // Only sync indexes in development env while it's not possible to create complex indexes directly from models - // In other environments it will simply create missing indexes (those defined in the models but not present in db) - if (strapi.app.env === 'development') { + // Only sync indexes when not in production env while it's not possible to create complex indexes directly from models + // In production it will simply create missing indexes (those defined in the models but not present in db) + if (strapi.app.env !== 'production') { // Ensure indexes are synced with the model, prevent duplicate index errors // Side-effect: Delete all the indexes not present in the model.json Model.syncIndexes(null, handleIndexesErrors); diff --git a/packages/strapi-database/lib/connector-registry.js b/packages/strapi-database/lib/connector-registry.js index b1c57871f9..6d8f107f70 100644 --- a/packages/strapi-database/lib/connector-registry.js +++ b/packages/strapi-database/lib/connector-registry.js @@ -51,7 +51,7 @@ const createConnectorRegistry = ({ defaultConnection, connections }) => { getByConnection(connection) { if (!_.has(connections, connection)) { - throw new Error('Trying to access a connector for an unknow connection'); + throw new Error('Trying to access a connector for an unknown connection'); } const connectorKey = connections[connection].connector; diff --git a/packages/strapi/lib/Strapi.js b/packages/strapi/lib/Strapi.js index 6b87293885..412b15a2d2 100644 --- a/packages/strapi/lib/Strapi.js +++ b/packages/strapi/lib/Strapi.js @@ -201,7 +201,9 @@ class Strapi { } async destroy() { - this.server.destroy(); + if (_.has(this, 'server.destroy')) { + this.server.destroy(); + } if (_.has(this, 'db')) { await this.db.destroy(); @@ -417,10 +419,9 @@ class Strapi { // plugins bootstrap const pluginBoostraps = Object.keys(this.plugins).map(plugin => { return execBootstrap(_.get(this.plugins[plugin], 'config.functions.bootstrap')).catch(err => { - // console.log(err); strapi.log.error(`Bootstrap function in plugin "${plugin}" failed`); strapi.log.error(err); - // strapi.stop(); + strapi.stop(); }); }); await Promise.all(pluginBoostraps); @@ -433,7 +434,7 @@ class Strapi { return execBootstrap(adminBootstrap).catch(err => { strapi.log.error(`Bootstrap function in admin failed`); strapi.log.error(err); - // strapi.stop(); + strapi.stop(); }); }