airqo-platform / airqo-platform/AirQo-api

[Device Registry] Refactor database connections to lazy loading pattern

Đang mở
#4,520 0 bình luận 0 reaction 1 người được giao Được @Baalmart nhận Xem trên GitHub
Ngôn ngữ chính
JavaScript
Star
26
Fork
24
Merge trung bình
5 giờ 36 phút
Pull request đã merge (30 ngày)
81

Mô tả

## 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)

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Đánh giá

Issue này chưa được đánh giá.

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.