dt-common-device 3.0.9 → 3.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/dist/config/config.d.ts +1 -2
  2. package/dist/config/config.js +4 -5
  3. package/dist/device/cloud/interface.d.ts +101 -0
  4. package/dist/device/cloud/interface.js +3 -0
  5. package/dist/device/cloud/interfaces/IDeviceConnectionService.d.ts +7 -0
  6. package/dist/device/cloud/interfaces/IDeviceConnectionService.js +3 -0
  7. package/dist/device/cloud/interfaces/IDevicesService.d.ts +9 -0
  8. package/dist/device/cloud/services/Device.service.d.ts +39 -0
  9. package/dist/device/cloud/services/Device.service.js +9 -0
  10. package/dist/device/cloud/services/DeviceCloudService.d.ts +42 -0
  11. package/dist/device/cloud/services/DeviceCloudService.js +59 -0
  12. package/dist/device/cloud/services/DeviceHub.service.d.ts +3 -0
  13. package/dist/device/cloud/services/DeviceHub.service.js +6 -0
  14. package/dist/device/cloud/services/Hub.service.d.ts +25 -0
  15. package/dist/device/cloud/services/Hub.service.js +9 -0
  16. package/dist/device/cloud/services/SmartThingsDeviceService.d.ts +38 -0
  17. package/dist/device/cloud/services/SmartThingsDeviceService.js +52 -0
  18. package/dist/device/index.d.ts +4 -0
  19. package/dist/device/index.js +20 -0
  20. package/dist/device/local/events/EventHandler.js +6 -6
  21. package/dist/device/local/events/Events.d.ts +12 -33
  22. package/dist/device/local/events/Events.js +12 -33
  23. package/dist/device/local/interface.d.ts +0 -0
  24. package/dist/device/local/interface.js +1 -0
  25. package/dist/device/local/interfaces/IDevice.d.ts +1 -0
  26. package/dist/device/local/repository/Schedule.repository.d.ts +0 -1
  27. package/dist/device/local/repository/Schedule.repository.js +6 -6
  28. package/dist/device/local/services/DeviceHub.service.d.ts +11 -0
  29. package/dist/device/local/services/DeviceHub.service.js +40 -0
  30. package/dist/queue/entities/HybridHttpQueue.d.ts +4 -14
  31. package/dist/queue/entities/HybridHttpQueue.js +31 -119
  32. package/dist/queue/interfaces/IHybridHttpQueue.d.ts +2 -12
  33. package/dist/queue/interfaces/IJobResult.d.ts +1 -8
  34. package/dist/queue/interfaces/index.d.ts +0 -1
  35. package/dist/queue/interfaces/index.js +0 -1
  36. package/dist/queue/services/QueueService.d.ts +2 -12
  37. package/dist/queue/types/queue.types.d.ts +10 -29
  38. package/dist/queue/utils/jobUtils.d.ts +0 -3
  39. package/dist/queue/utils/jobUtils.js +0 -48
  40. package/dist/queue/utils/queueUtils.d.ts +7 -0
  41. package/dist/queue/utils/queueUtils.js +113 -4
  42. package/package.json +6 -1
  43. package/.eslintrc.js +0 -44
  44. package/dist/audit/AuditProperties.d.ts +0 -16
  45. package/dist/audit/AuditUtils.d.ts +0 -2
  46. package/dist/audit/AuditUtils.js +0 -36
  47. package/src/alerts/Alert.model.ts +0 -289
  48. package/src/alerts/Alert.repository.ts +0 -487
  49. package/src/alerts/Alert.service.ts +0 -711
  50. package/src/alerts/AlertBuilder.example.ts +0 -126
  51. package/src/alerts/AlertBuilder.ts +0 -208
  52. package/src/alerts/AlertService.example.ts +0 -232
  53. package/src/alerts/alert.types.ts +0 -64
  54. package/src/alerts/index.ts +0 -3
  55. package/src/audit/AuditProperties.ts +0 -16
  56. package/src/audit/AuditUtils.ts +0 -38
  57. package/src/config/config.ts +0 -202
  58. package/src/config/config.types.ts +0 -21
  59. package/src/connection/Connection.repository.ts +0 -52
  60. package/src/connection/Connection.service.ts +0 -39
  61. package/src/connection/IConnection.ts +0 -27
  62. package/src/connection/index.ts +0 -3
  63. package/src/constants/ConnectionProviders.ts +0 -11
  64. package/src/constants/Event.ts +0 -89
  65. package/src/constants/Service.ts +0 -17
  66. package/src/constants/index.ts +0 -3
  67. package/src/db/db.ts +0 -24
  68. package/src/db/index.ts +0 -2
  69. package/src/db/redis.ts +0 -20
  70. package/src/device/cloud/entities/CloudDevice.ts +0 -40
  71. package/src/device/cloud/entities/CloudDeviceService.ts +0 -8
  72. package/src/device/cloud/entities/DeviceFactory.ts +0 -27
  73. package/src/device/cloud/entities/index.ts +0 -3
  74. package/src/device/cloud/interfaces/ICloudDevice.ts +0 -14
  75. package/src/device/cloud/interfaces/ICloudDeviceService.ts +0 -6
  76. package/src/device/cloud/interfaces/IDeviceFactory.ts +0 -5
  77. package/src/device/cloud/interfaces/IRawDataTransformer.ts +0 -5
  78. package/src/device/cloud/interfaces/IRawDevice.ts +0 -19
  79. package/src/device/cloud/interfaces/index.ts +0 -5
  80. package/src/device/local/interfaces/IDevice.ts +0 -61
  81. package/src/device/local/interfaces/IDtDevice.ts +0 -16
  82. package/src/device/local/interfaces/ISchedule.ts +0 -40
  83. package/src/device/local/interfaces/index.ts +0 -3
  84. package/src/device/local/repository/Device.repository.ts +0 -368
  85. package/src/device/local/repository/Hub.repository.ts +0 -107
  86. package/src/device/local/repository/Schedule.repository.ts +0 -72
  87. package/src/device/local/services/Device.service.ts +0 -436
  88. package/src/device/local/services/Hub.service.ts +0 -57
  89. package/src/device/local/services/Schedule.service.ts +0 -26
  90. package/src/device/local/services/index.ts +0 -3
  91. package/src/docs/Alert.model.md +0 -319
  92. package/src/docs/Alerts&IssuesModel.md +0 -312
  93. package/src/docs/Issue.model.md +0 -386
  94. package/src/docs/SECURITY.md +0 -67
  95. package/src/docs/TROUBLESHOOTING.md +0 -184
  96. package/src/events/BaseEventHandler.ts +0 -145
  97. package/src/events/BaseEventTransformer.ts +0 -97
  98. package/src/events/DeviceEventHandler.ts +0 -213
  99. package/src/events/DeviceEventTransformerFactory.ts +0 -77
  100. package/src/events/EventHandler.ts +0 -124
  101. package/src/events/EventHandlerOrchestrator.ts +0 -119
  102. package/src/events/EventProcessingService.ts +0 -248
  103. package/src/events/InternalEventSubscription.ts +0 -194
  104. package/src/events/index.ts +0 -9
  105. package/src/events/interfaces/DeviceEvent.ts +0 -56
  106. package/src/events/interfaces/IEventHandler.ts +0 -28
  107. package/src/events/interfaces/IEventTransformer.ts +0 -8
  108. package/src/events/interfaces/IInternalEvent.ts +0 -33
  109. package/src/events/interfaces/index.ts +0 -4
  110. package/src/index.ts +0 -43
  111. package/src/issues/Issue.model.ts +0 -350
  112. package/src/issues/Issue.repository.ts +0 -517
  113. package/src/issues/Issue.service.ts +0 -932
  114. package/src/issues/IssueBuilder.example.ts +0 -210
  115. package/src/issues/IssueBuilder.ts +0 -263
  116. package/src/issues/IssueService.example.ts +0 -310
  117. package/src/issues/index.ts +0 -2
  118. package/src/issues/issue.types.ts +0 -98
  119. package/src/property/IProperty.ts +0 -30
  120. package/src/property/Property.repository.ts +0 -53
  121. package/src/property/Property.service.ts +0 -38
  122. package/src/property/index.ts +0 -2
  123. package/src/queue/entities/HybridHttpQueue.ts +0 -274
  124. package/src/queue/entities/index.ts +0 -1
  125. package/src/queue/index.ts +0 -6
  126. package/src/queue/interfaces/IHttpRequestJob.ts +0 -10
  127. package/src/queue/interfaces/IHybridHttpQueue.ts +0 -25
  128. package/src/queue/interfaces/IJobResult.ts +0 -15
  129. package/src/queue/interfaces/IRateLimitConfig.ts +0 -5
  130. package/src/queue/interfaces/index.ts +0 -4
  131. package/src/queue/services/QueueService.ts +0 -40
  132. package/src/queue/services/index.ts +0 -1
  133. package/src/queue/types/http.types.ts +0 -23
  134. package/src/queue/types/index.ts +0 -2
  135. package/src/queue/types/queue.types.ts +0 -21
  136. package/src/queue/utils/index.ts +0 -3
  137. package/src/queue/utils/jobUtils.ts +0 -79
  138. package/src/queue/utils/queueUtils.ts +0 -84
  139. package/src/queue/utils/rateLimit.utils.ts +0 -131
  140. package/src/utils/http.utils.ts +0 -143
  141. package/src/utils/index.ts +0 -2
  142. package/src/utils/redis.utils.ts +0 -74
  143. package/tsconfig.json +0 -20
  144. /package/dist/{audit/AuditProperties.js → device/cloud/interfaces/IDevicesService.js} +0 -0
@@ -1,386 +0,0 @@
1
- # Issue Model Documentation
2
-
3
- This document describes the Mongoose implementation of the Issue model, which was converted from a Prisma schema to provide comprehensive issue tracking functionality.
4
-
5
- ## Overview
6
-
7
- The Issue model provides a complete issue tracking system with the following features:
8
-
9
- - **Issue Management**: Create, read, update, and delete issues
10
- - **Status Tracking**: Track issue status from OPEN to CLOSED
11
- - **Priority Levels**: Assign priority levels (LOW, MEDIUM, HIGH, CRITICAL)
12
- - **Categories**: Categorize issues (TECHNICAL, OPERATIONAL, etc.)
13
- - **Entity References**: Link issues to various entities (DEVICE, HUB, etc.)
14
- - **Assignment**: Assign issues to users for resolution
15
- - **Comments**: Add, update, and remove comments on issues
16
- - **Due Dates**: Set and track due dates for issues
17
- - **Soft Deletion**: Support for soft deletion with recovery capability
18
- - **Search**: Full-text search across issue titles and descriptions
19
- - **Statistics**: Comprehensive issue statistics and reporting
20
-
21
- ## Model Structure
22
-
23
- ### Core Fields
24
-
25
- | Field | Type | Required | Description |
26
- | ------------- | -------------- | -------- | --------------------------------------------- |
27
- | `_id` | String | Yes | MongoDB ObjectId (auto-generated) |
28
- | `category` | IssueCategory | Yes | Issue category (TECHNICAL, OPERATIONAL, etc.) |
29
- | `propertyId` | String | Yes | Property UUID reference |
30
- | `title` | String | Yes | Issue title |
31
- | `description` | String | Yes | Issue description |
32
- | `entityId` | String | No | Generic entity reference UUID |
33
- | `entityType` | EntityType | Yes | Entity type (DEVICE, HUB, etc.) |
34
- | `priority` | IssuePriority | Yes | Issue priority (default: MEDIUM) |
35
- | `status` | IssueStatus | Yes | Issue status (default: OPEN) |
36
- | `assignedTo` | String | No | User UUID assigned to resolve |
37
- | `resolvedBy` | String | No | User UUID who resolved the issue |
38
- | `resolvedAt` | Date | No | Resolution timestamp |
39
- | `dueDate` | Date | No | Due date for resolution |
40
- | `isDeleted` | Boolean | Yes | Soft deletion flag (default: false) |
41
- | `createdBy` | String | Yes | User UUID who created the issue |
42
- | `updatedBy` | String | No | User UUID who last updated |
43
- | `createdAt` | Date | Yes | Creation timestamp |
44
- | `updatedAt` | Date | Yes | Last update timestamp |
45
- | `comments` | IssueComment[] | No | Array of comments |
46
-
47
- ### Enums
48
-
49
- #### IssueCategory
50
-
51
- ```typescript
52
- enum IssueCategory {
53
- READINESS = "READINESS",
54
- OPERATIONS = "OPERATIONS",
55
- SECURITY = "SECURITY",
56
- ENERGY = "ENERGY",
57
- OTHER = "OTHER",
58
- }
59
- ```
60
-
61
- #### IssuePriority
62
-
63
- ```typescript
64
- enum IssuePriority {
65
- LOW = "LOW",
66
- MEDIUM = "MEDIUM",
67
- HIGH = "HIGH",
68
- CRITICAL = "CRITICAL",
69
- }
70
- ```
71
-
72
- #### IssueStatus
73
-
74
- ```typescript
75
- enum IssueStatus {
76
- OPEN = "OPEN",
77
- IN_PROGRESS = "IN_PROGRESS",
78
- RESOLVED = "RESOLVED",
79
- CLOSED = "CLOSED",
80
- }
81
- ```
82
-
83
- #### EntityType
84
-
85
- ```typescript
86
- enum EntityType {
87
- DEVICE = "DEVICE",
88
- COLLECTION = "COLLECTION",
89
- USER = "USER",
90
- INTEGRATION = "INTEGRATION",
91
- PROPERTY = "PROPERTY",
92
- HUB = "HUB",
93
- SCHEDULE = "SCHEDULE",
94
- ALERT = "ALERT",
95
- OTHER = "OTHER",
96
- }
97
- ```
98
-
99
- ### Comment Structure
100
-
101
- ```typescript
102
- interface IssueComment {
103
- id: string;
104
- userId: string;
105
- content: string;
106
- createdAt: Date;
107
- updatedAt?: Date;
108
- }
109
- ```
110
-
111
- ## Usage Examples
112
-
113
- ### Basic CRUD Operations
114
-
115
- #### Creating an Issue
116
-
117
- ```typescript
118
- import { IssueService } from "../services/Issue.service";
119
- import {
120
- IssueCategory,
121
- EntityType,
122
- IssuePriority,
123
- } from "../../../types/issue.types";
124
-
125
- const issueService = new IssueService();
126
-
127
- const newIssue = await issueService.createIssue({
128
- category: IssueCategory.READINESS,
129
- propertyId: "property-uuid",
130
- title: "Device connectivity issue",
131
- description: "Device is not responding to commands",
132
- entityId: "device-uuid",
133
- entityType: EntityType.DEVICE,
134
- priority: IssuePriority.HIGH,
135
- createdBy: "user-uuid",
136
- dueDate: new Date("2024-01-15"),
137
- });
138
- ```
139
-
140
- #### Getting Issues
141
-
142
- ```typescript
143
- // Get all issues for a property
144
- const propertyIssues = await issueService.getIssuesByProperty("property-uuid");
145
-
146
- // Get issues assigned to a user
147
- const assignedIssues = await issueService.getIssuesByAssignee("user-uuid");
148
-
149
- // Get issues by status
150
- const openIssues = await issueService.getIssuesByStatus(IssueStatus.OPEN);
151
-
152
- // Get issues with filters
153
- const filteredIssues = await issueService.getIssues({
154
- propertyId: "property-uuid",
155
- status: IssueStatus.IN_PROGRESS,
156
- priority: IssuePriority.HIGH,
157
- limit: 10,
158
- skip: 0,
159
- });
160
- ```
161
-
162
- #### Updating an Issue
163
-
164
- ```typescript
165
- // Update issue status
166
- await issueService.updateIssue(issueId, {
167
- status: IssueStatus.IN_PROGRESS,
168
- updatedBy: "user-uuid",
169
- });
170
-
171
- // Assign issue to user
172
- await issueService.assignIssue(issueId, "assignee-uuid", "assigned-by-uuid");
173
-
174
- // Resolve issue
175
- await issueService.resolveIssue(
176
- issueId,
177
- "resolved-by-uuid",
178
- "Issue resolved successfully"
179
- );
180
-
181
- // Close issue
182
- await issueService.closeIssue(issueId, "closed-by-uuid");
183
- ```
184
-
185
- #### Adding Comments
186
-
187
- ```typescript
188
- // Add a comment
189
- await issueService.addComment(issueId, {
190
- userId: "user-uuid",
191
- content: "Investigation in progress",
192
- });
193
-
194
- // Update a comment
195
- await issueService.updateComment(
196
- issueId,
197
- commentId,
198
- "Updated content",
199
- "user-uuid"
200
- );
201
-
202
- // Remove a comment
203
- await issueService.removeComment(issueId, commentId);
204
- ```
205
-
206
- ### Advanced Operations
207
-
208
- #### Search Issues
209
-
210
- ```typescript
211
- // Search by text
212
- const searchResults = await issueService.searchIssues("connectivity", {
213
- propertyId: "property-uuid",
214
- limit: 20,
215
- });
216
- ```
217
-
218
- #### Get Statistics
219
-
220
- ```typescript
221
- // Get overall statistics
222
- const stats = await issueService.getIssueStatistics();
223
-
224
- // Get property-specific statistics
225
- const propertyStats = await issueService.getIssueStatistics("property-uuid");
226
-
227
- console.log(`Total issues: ${stats.total}`);
228
- console.log(`Open issues: ${stats.open}`);
229
- console.log(`Overdue issues: ${stats.overdue}`);
230
- console.log(`High priority: ${stats.byPriority.HIGH}`);
231
- console.log(`Readiness issues: ${stats.byCategory.READINESS}`);
232
- ```
233
-
234
- #### Find Overdue Issues
235
-
236
- ```typescript
237
- // Get all overdue issues
238
- const overdueIssues = await issueService.getOverdueIssues();
239
-
240
- // Get upcoming issues (due within 7 days)
241
- const upcomingIssues = await issueService.getUpcomingIssues(7);
242
- ```
243
-
244
- #### Repository Pattern Usage
245
-
246
- For more advanced data access patterns, use the repository:
247
-
248
- ```typescript
249
- import { IssueRepository } from "../repository/Issue.repository";
250
-
251
- const issueRepo = new IssueRepository();
252
-
253
- // Bulk operations
254
- await issueRepo.bulkUpdate(["issue1", "issue2"], {
255
- status: IssueStatus.CLOSED,
256
- updatedBy: "user-uuid",
257
- });
258
-
259
- // Count issues
260
- const count = await issueRepo.count({
261
- propertyId: "property-uuid",
262
- status: IssueStatus.OPEN,
263
- });
264
-
265
- // Advanced filtering with sorting
266
- const issues = await issueRepo.findAll({
267
- propertyId: "property-uuid",
268
- sort: { priority: -1, createdAt: -1 },
269
- limit: 50,
270
- });
271
- ```
272
-
273
- ## Business Rules
274
-
275
- ### Status Transitions
276
-
277
- Issues follow a specific status flow:
278
-
279
- 1. **OPEN** → **IN_PROGRESS** (requires assignment)
280
- 2. **IN_PROGRESS** → **RESOLVED** (requires resolution note)
281
- 3. **RESOLVED** → **CLOSED** (final state)
282
- 4. **RESOLVED** → **OPEN** (reopen allowed)
283
- 5. **CLOSED** → **OPEN** (reopen allowed)
284
-
285
- ### Assignment Requirements
286
-
287
- - Issues must be assigned before moving to IN_PROGRESS status
288
- - Only assigned issues can be moved to IN_PROGRESS
289
- - Unassigned issues remain in OPEN status
290
-
291
- ### Resolution Requirements
292
-
293
- - Issues must have a resolution note when moved to RESOLVED status
294
- - Resolution automatically sets the `resolvedAt` timestamp
295
- - Resolution automatically sets the `resolvedBy` user
296
-
297
- ### Overdue Calculation
298
-
299
- Issues are considered overdue based on priority:
300
-
301
- | Priority | Overdue After |
302
- | -------- | ------------- |
303
- | LOW | 14 days |
304
- | MEDIUM | 7 days |
305
- | HIGH | 3 days |
306
- | CRITICAL | 1 day |
307
-
308
- ### Priority Management
309
-
310
- - Priority can be changed at any time
311
- - Priority changes are logged for audit purposes
312
- - Critical priority issues get special handling
313
-
314
- ## Indexes
315
-
316
- The model includes the following indexes for optimal performance:
317
-
318
- - `propertyId` (single field)
319
- - `assignedTo` (single field)
320
- - `entityId` (single field)
321
- - `entityType` (single field)
322
- - `status` (single field)
323
- - `priority` (single field)
324
- - `createdAt` (single field)
325
- - `{ propertyId: 1, status: 1, priority: 1 }` (compound)
326
- - `{ assignedTo: 1, status: 1 }` (compound)
327
- - `{ entityId: 1, entityType: 1 }` (compound)
328
-
329
- ## Middleware
330
-
331
- The model includes pre-save and pre-update middleware that automatically:
332
-
333
- - Updates the `updatedAt` timestamp on save
334
- - Updates the `updatedAt` timestamp on update operations
335
- - Validates status transitions
336
- - Validates assignment requirements
337
-
338
- ## Virtual Fields
339
-
340
- - `isOverdue`: Returns `true` if the issue is overdue
341
- - `timeToResolution`: Calculates time to resolution (if resolved)
342
- - `isAssigned`: Returns `true` if the issue is assigned
343
-
344
- ## Error Handling
345
-
346
- All operations include comprehensive error handling with descriptive error messages. The service and repository layers wrap database operations in try-catch blocks and provide meaningful error messages.
347
-
348
- Common error scenarios:
349
-
350
- - **Invalid status transition**: "Cannot transition from OPEN to RESOLVED"
351
- - **Missing assignment**: "Issue must be assigned before moving to IN_PROGRESS"
352
- - **Missing resolution**: "Resolution note is required when resolving an issue"
353
- - **Invalid due date**: "Due date must be in the future"
354
- - **Missing required fields**: "Issue title must be at least 3 characters long"
355
-
356
- ## Best Practices
357
-
358
- 1. **Set Realistic Due Dates**: Set achievable due dates for better tracking
359
- 2. **Use Appropriate Categories**: Properly categorize issues for better organization
360
- 3. **Assign Issues Promptly**: Assign issues to appropriate users quickly
361
- 4. **Add Meaningful Comments**: Use comments to track progress and communication
362
- 5. **Monitor Overdue Issues**: Regularly check for overdue issues
363
- 6. **Use Priority Wisely**: Don't overuse high/critical priority
364
- 7. **Provide Resolution Notes**: Always include detailed resolution notes
365
- 8. **Use Soft Deletion**: Always use soft deletion for audit trails
366
- 9. **Validate Input**: Always validate issue data before creation
367
- 10. **Monitor Statistics**: Regularly check issue statistics for insights
368
-
369
- ## Migration from Prisma
370
-
371
- This Mongoose model maintains full compatibility with the original Prisma schema:
372
-
373
- - All fields and types are preserved
374
- - Indexes match the Prisma schema
375
- - Relationships are maintained through foreign key references
376
- - Collection name matches Prisma (`dt_issues`)
377
-
378
- The model provides additional features beyond the Prisma schema:
379
-
380
- - Instance methods for common operations
381
- - Static methods for complex queries
382
- - Virtual fields for computed properties
383
- - Comprehensive business logic validation
384
- - Built-in monitoring and logging
385
- - Comment management system
386
- - Overdue calculation logic
@@ -1,67 +0,0 @@
1
- # Security Policy
2
-
3
- ## Supported Versions
4
-
5
- | Version | Supported |
6
- | ------- | ------------------ |
7
- | 1.0.x | :white_check_mark: |
8
-
9
- ## Reporting a Vulnerability
10
-
11
- If you discover a security vulnerability within dt-common-device, please send an email to security@devicethread.com. All security vulnerabilities will be promptly addressed.
12
-
13
- ## Security Features
14
-
15
- ### Input Validation
16
-
17
- - All user inputs are validated and sanitized
18
- - Device IDs and Property IDs are validated for format and length
19
- - Metadata is sanitized to prevent injection attacks
20
- - URL validation for all external service endpoints
21
-
22
- ### Error Handling
23
-
24
- - Custom error classes for different types of failures
25
- - No sensitive information leaked in error messages
26
- - Proper HTTP status code mapping
27
- - Graceful degradation for network failures
28
-
29
- ### Type Safety
30
-
31
- - Full TypeScript support with strict typing
32
- - No `any` types in public APIs
33
- - Interface validation for all data structures
34
-
35
- ### Network Security
36
-
37
- - HTTPS enforcement for all external calls
38
- - Request timeout handling
39
- - Retry logic for transient failures
40
- - Proper error classification for different HTTP status codes
41
-
42
- ## Best Practices
43
-
44
- 1. **Always validate inputs** before passing to library methods
45
- 2. **Handle errors appropriately** using the provided error classes
46
- 3. **Use HTTPS** for all external service URLs
47
- 4. **Keep dependencies updated** by running `npm audit` regularly
48
- 5. **Monitor for security updates** in dependent packages
49
-
50
- ## Dependencies
51
-
52
- This library uses the following security-focused dependencies:
53
-
54
- - `axios` - HTTP client with built-in security features
55
- - `lodash` - Utility library with security patches
56
- - Custom validation utilities for input sanitization
57
-
58
- ## Vulnerability Prevention
59
-
60
- - Regular security audits with `npm audit`
61
- - Automated vulnerability scanning in CI/CD
62
- - Input validation and sanitization
63
- - Type-safe interfaces
64
- - Comprehensive error handling
65
- - No eval() or dynamic code execution
66
- - No direct file system access
67
- - No command injection vulnerabilities
@@ -1,184 +0,0 @@
1
- # Troubleshooting Guide
2
-
3
- ## HTTP Request Issues
4
-
5
- ### Error: `TypeError: Cannot read properties of undefined (reading 'emit')`
6
-
7
- This error typically occurs when HTTP requests fail due to network connectivity issues, invalid service URLs, or request timeouts.
8
-
9
- #### Common Causes:
10
-
11
- 1. **Invalid or unreachable DEVICE_SERVICE URL**
12
- 2. **Network connectivity issues**
13
- 3. **Service is down or not responding**
14
- 4. **Request timeout (default: 30 seconds)**
15
- 5. **DNS resolution failures**
16
-
17
- #### Solutions:
18
-
19
- 1. **Check Service URL Configuration**
20
-
21
- ```typescript
22
- // Ensure DEVICE_SERVICE URL is properly configured
23
- const config: IConfig = {
24
- DEVICE_SERVICE: "http://localhost:3000", // or your actual service URL
25
- // ... other config
26
- };
27
- ```
28
-
29
- 2. **Verify Network Connectivity**
30
-
31
- ```bash
32
- # Test if the service is reachable
33
- curl -v http://your-device-service-url/health
34
- ```
35
-
36
- 3. **Check Service Status**
37
-
38
- - Ensure the device service is running
39
- - Check if the service is listening on the correct port
40
- - Verify firewall settings
41
-
42
- 4. **Enable Debug Logging**
43
- ```typescript
44
- const config: IConfig = {
45
- LOGGER: {
46
- info: (msg, ...args) => console.log(msg, ...args),
47
- warn: (msg, ...args) => console.warn(msg, ...args),
48
- error: (msg, ...args) => console.error(msg, ...args),
49
- },
50
- // ... other config
51
- };
52
- ```
53
-
54
- #### Recent Fixes Applied:
55
-
56
- 1. **Centralized Axios Instance**: All HTTP requests now use a single, properly configured axios instance
57
- 2. **Added Request Timeouts**: All HTTP requests have a 30-second timeout
58
- 3. **Improved Error Handling**: Better error messages with context
59
- 4. **Request/Response Interceptors**: Added logging for debugging
60
- 5. **URL Validation**: Service URLs are validated during initialization
61
- 6. **Retry Logic**: Failed requests can be retried with exponential backoff
62
-
63
- #### Architecture Changes:
64
-
65
- **Before**: Each repository created its own axios instance
66
-
67
- ```typescript
68
- // Old approach - each repository had its own axios setup
69
- export class DeviceRepository {
70
- private readonly axiosInstance;
71
-
72
- constructor() {
73
- this.axiosInstance = axios.create({
74
- timeout: 30000,
75
- // ... other config
76
- });
77
- // ... interceptors setup
78
- }
79
- }
80
- ```
81
-
82
- **After**: Centralized axios instance shared across all repositories
83
-
84
- ```typescript
85
- // New approach - centralized axios instance
86
- import { getDeviceServiceAxiosInstance } from "../../../utils/http-utils";
87
-
88
- export class DeviceRepository {
89
- private readonly axiosInstance;
90
-
91
- constructor() {
92
- this.axiosInstance = getDeviceServiceAxiosInstance();
93
- }
94
- }
95
- ```
96
-
97
- #### Benefits of Centralized Approach:
98
-
99
- 1. **Consistency**: All HTTP requests use the same configuration
100
- 2. **Maintainability**: Configuration changes only need to be made in one place
101
- 3. **Performance**: Single instance reduces memory usage
102
- 4. **Error Handling**: Centralized error handling and logging
103
- 5. **Testing**: Easier to mock and test HTTP requests
104
-
105
- #### Debugging Steps:
106
-
107
- 1. **Check Logs**: Look for detailed error messages in the logs
108
- 2. **Verify Configuration**: Ensure all required environment variables are set
109
- 3. **Test Connectivity**: Use curl or similar tools to test service endpoints
110
- 4. **Check Network**: Verify network connectivity and DNS resolution
111
-
112
- #### Environment Variables Required:
113
-
114
- ```bash
115
- # Required for HTTP requests
116
- DEVICE_SERVICE=http://your-device-service-url
117
-
118
- # Required for database connections
119
- ADMIN_DB_URI=postgresql://...
120
- MONGODB_URI=mongodb://...
121
- REDIS_HOST=localhost
122
- REDIS_PORT=6379
123
-
124
- # Required for AWS services
125
- AWS_ACCESS_KEY_ID=your-access-key
126
- AWS_SECRET_ACCESS_KEY=your-secret-key
127
- AWS_REGION=your-region
128
- EVENT_BUS_NAME=your-event-bus
129
-
130
- # Required for analytics
131
- POSTHOG_API_KEY=your-api-key
132
- POSTHOG_HOST=your-posthog-host
133
- ```
134
-
135
- #### Example Error Handling:
136
-
137
- ```typescript
138
- import { initialize } from "dt-common-device";
139
-
140
- try {
141
- await initialize({
142
- DEVICE_SERVICE: "http://localhost:3000",
143
- LOGGER: console,
144
- // ... other config
145
- });
146
- } catch (error) {
147
- console.error("Initialization failed:", error.message);
148
- // Handle initialization error
149
- }
150
- ```
151
-
152
- #### Repository Error Handling:
153
-
154
- All repository classes now include:
155
-
156
- - Proper try-catch blocks
157
- - Detailed error logging
158
- - Request timeouts
159
- - Response validation
160
- - Network error detection
161
- - Centralized axios instance usage
162
-
163
- #### Affected Files:
164
-
165
- The following repository files now use the centralized axios instance:
166
-
167
- - `src/device/local/repository/Device.repository.ts`
168
- - `src/device/local/repository/Hub.repository.ts`
169
- - `src/device/local/repository/Schedule.repository.ts`
170
-
171
- Other repository files (Alert, Issue, Property, Connection) use database operations and don't require HTTP requests.
172
-
173
- #### HTTP Utilities:
174
-
175
- The centralized axios instance is managed in:
176
-
177
- - `src/utils/http-utils.ts` - Contains the axios instance creation and configuration
178
-
179
- If you continue to experience issues, please:
180
-
181
- 1. Check the service logs for detailed error messages
182
- 2. Verify all environment variables are correctly set
183
- 3. Test network connectivity to the service endpoints
184
- 4. Ensure the target services are running and accessible