From afdc19bf9839e83d12ff422f12bc90efae6cdcf6 Mon Sep 17 00:00:00 2001 From: Dominique Emond Date: Thu, 1 Aug 2019 16:54:44 -0400 Subject: [PATCH] fix: prevent max listeners warning If establishing a database connection is slow and database migration runs and there are many models, sql operations are queued up and this leads to the node.js max emitters exceeded warning. A default value for max emitters has now been introduced, and it can also be configured in datasources.json. Signed-off-by: Dominique Emond --- lib/datasource.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/lib/datasource.js b/lib/datasource.js index 6b6fe32e8..a3f678091 100644 --- a/lib/datasource.js +++ b/lib/datasource.js @@ -207,6 +207,11 @@ DataSource.prototype._setupConnector = function() { this.connector.dataSource = this; } const dataSource = this; + + // Set max listeners to a default/configured value + // solves bug https://github.com/strongloop/loopback-next/issues/2198 + dataSource.setMaxListeners(dataSource.getMaxOfflineRequests()); + this.connector.log = function(query, start) { dataSource.log(query, start); }; @@ -2699,6 +2704,22 @@ DataSource.prototype.beginTransaction = function(options) { return Transaction.begin(this.connector, options); }; +/** + * Get the maximum number of event listeners + */ +DataSource.prototype.getMaxOfflineRequests = function() { + // Set max listeners to a default value + // Override this default value with a datasource setting + // 'maxOfflineRequests' from an application's datasources.json + // solves bug https://github.com/strongloop/loopback-next/issues/2198 + let maxOfflineRequests = 16; + if (this.settings && this.settings.maxOfflineRequests) { + if (this.settings.maxOfflineRequests > maxOfflineRequests) + maxOfflineRequests = this.settings.maxOfflineRequests; + } + return maxOfflineRequests; +}; + /*! The hidden property call is too expensive so it is not used that much */ /**