airqo-platform / airqo-platform/AirQo-api

[Device Registry] Refactor database connections to lazy loading pattern

Offen
#4,520 0 Kommentare 0 Reaktionen 1 zugewiesene Person Beansprucht von @Baalmart Auf GitHub ansehen
Vorherrschende Sprache
JavaScript
Sterne
26
Forks
24
Ø Merge
5 Std. 36 Min.
Gemergte PRs (30 T.)
81

Beschreibung

## Background

In PR #4513 (https://github.com/airqo-platform/AirQo-api/pull/4513), the following refactor suggestion was identified:

**Immediate connection invocation may cause issues with module imports.**

Initializing the database connections immediately when the module is loaded could cause problems in testing scenarios or when the module is imported but not yet ready to connect to the database.

## Proposed Changes

Refactor the database connections in `src/device-registry/config/database.js` to use lazy-loading pattern:

```diff
- // Initialize both database connections
- const { commandDB: commandMongoDB, queryDB: queryMongoDB } = connectToMongoDB();
+ // Database connection instances
+ let commandMongoDB = null;
+ let queryMongoDB = null;
+
+ // Initialize database connections explicitly
+ function initializeConnections() {
+ if (!commandMongoDB || !queryMongoDB) {
+ const connections = connectToMongoDB();
+ commandMongoDB = connections.commandDB;
+ queryMongoDB = connections.queryDB;
+ }
+ return { commandMongoDB, queryMongoDB };
+ }
```

Then update each DB access function to call initializeConnections() if needed:

```diff
function getCommandTenantDB(tenantId, modelName, schema) {
const dbName = `${constants.DB_NAME}_command_${tenantId}`;
+ if (!commandMongoDB) {
+ initializeConnections();
+ }
if (commandMongoDB) {
// rest of function
```

## Benefits
- Improves testability
- Avoids issues when the module is imported but not yet ready to connect to the database
- Makes database connections lazy-loaded

## Related PR
This issue was referenced in PR #4513 (https://github.com/airqo-platform/AirQo-api/pull/4513#discussion_r1977804219)

Beitragsleitfaden

Beitragsleitfaden öffnen

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.