Fix mongoose destroy function & re-add strapi.stop calls

Signed-off-by: Convly <jean-sebastien.herbaux@epitech.eu>
This commit is contained in:
Convly 2020-11-27 15:58:50 +01:00
parent 987a7c1022
commit 823070df9d
4 changed files with 111 additions and 98 deletions

View File

@ -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,

View File

@ -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);

View File

@ -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;

View File

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