airqo-platform / airqo-platform/AirQo-api
[Device Registry] Refactor database connections to lazy loading pattern
- Lenguaje dominante
- JavaScript
- Estrellas
- 26
- Forks
- 24
- Merge medio
- 5 h 36 min
- PR fusionados (30 d)
- 81
Descripción
## 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)
Guía de contribución
Evaluación
Este issue todavía no se ha evaluado.