dt-common-device 2.0.0 → 2.0.2

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 (32) hide show
  1. package/dist/config/config.js +1 -1
  2. package/dist/db/redis.js +1 -0
  3. package/dist/device/cloud/entities/CloudDevice.d.ts +1 -0
  4. package/dist/device/cloud/entities/CloudDevice.js +3 -0
  5. package/dist/device/local/repository/Device.repository.d.ts +1 -0
  6. package/dist/device/local/repository/Device.repository.js +11 -1
  7. package/dist/device/local/repository/Hub.repository.js +1 -1
  8. package/dist/device/local/repository/Schedule.repository.js +1 -1
  9. package/dist/device/local/services/Device.service.d.ts +1 -1
  10. package/dist/device/local/services/Device.service.js +3 -1
  11. package/dist/events/EventHandler.js +6 -1
  12. package/dist/index.d.ts +1 -0
  13. package/dist/index.js +2 -0
  14. package/dist/utils/http.utils.d.ts +13 -0
  15. package/dist/utils/http.utils.js +117 -0
  16. package/dist/utils/index.d.ts +2 -0
  17. package/dist/utils/index.js +18 -0
  18. package/dist/utils/redis.utils.d.ts +8 -0
  19. package/dist/utils/redis.utils.js +123 -0
  20. package/package.json +1 -1
  21. package/src/config/config.ts +1 -1
  22. package/src/db/redis.ts +1 -0
  23. package/src/device/cloud/entities/CloudDevice.ts +4 -0
  24. package/src/device/local/repository/Device.repository.ts +13 -1
  25. package/src/device/local/repository/Hub.repository.ts +1 -1
  26. package/src/device/local/repository/Schedule.repository.ts +1 -1
  27. package/src/device/local/services/Device.service.ts +4 -2
  28. package/src/events/EventHandler.ts +6 -5
  29. package/src/index.ts +3 -0
  30. package/src/utils/index.ts +2 -0
  31. package/src/utils/redis.utils.ts +70 -0
  32. /package/src/utils/{http-utils.ts → http.utils.ts} +0 -0
@@ -16,7 +16,7 @@ const dt_audit_library_1 = require("dt-audit-library");
16
16
  const db_1 = require("../db/db");
17
17
  const dotenv_1 = __importDefault(require("dotenv"));
18
18
  const events_1 = require("../events");
19
- const http_utils_1 = require("../utils/http-utils");
19
+ const http_utils_1 = require("../utils/http.utils");
20
20
  dotenv_1.default.config();
21
21
  let config = null;
22
22
  let auditInitialized = false;
package/dist/db/redis.js CHANGED
@@ -7,6 +7,7 @@ exports.getRedisClient = getRedisClient;
7
7
  const config_1 = require("../config/config");
8
8
  const ioredis_1 = __importDefault(require("ioredis"));
9
9
  let redisClient = null;
10
+ //Singleton pattern to ensure only one Redis client instance is create only once and shared across the application
10
11
  function getRedisClient() {
11
12
  if (!redisClient) {
12
13
  const { host, port } = (0, config_1.getRedisDbHostAndPort)();
@@ -12,4 +12,5 @@ export declare abstract class CloudDevice implements ICloudDevice {
12
12
  getBattery(deviceId: string): Promise<number | string>;
13
13
  getState(deviceId: string): Promise<string>;
14
14
  getStatus(connectionId: string, deviceId: string): Promise<string>;
15
+ toLocalDevice(): Promise<IDevice>;
15
16
  }
@@ -19,5 +19,8 @@ class CloudDevice {
19
19
  async getStatus(connectionId, deviceId) {
20
20
  throw new Error("Method not implemented in Super Class.");
21
21
  }
22
+ async toLocalDevice() {
23
+ return {};
24
+ }
22
25
  }
23
26
  exports.CloudDevice = CloudDevice;
@@ -4,6 +4,7 @@ export declare class DeviceRepository {
4
4
  private readonly postgres;
5
5
  private readonly axiosInstance;
6
6
  constructor();
7
+ createDevice(body: IDevice): Promise<IDevice>;
7
8
  getDevice(deviceId: string, withHubDetails?: boolean): Promise<IDevice>;
8
9
  getDevices(deviceIds: string[], withHubDetails?: boolean): Promise<IDevice[]>;
9
10
  getPropertyDevices(propertyId: string, selectDeviceId?: boolean, type?: string, withHubDetails?: boolean): Promise<IDevice[]>;
@@ -42,7 +42,7 @@ exports.DeviceRepository = void 0;
42
42
  const config_1 = require("../../../config/config");
43
43
  const db_1 = require("../../../db");
44
44
  const typedi_1 = require("typedi");
45
- const http_utils_1 = require("../../../utils/http-utils");
45
+ const http_utils_1 = require("../../../utils/http.utils");
46
46
  let DeviceRepository = (() => {
47
47
  let _classDecorators = [(0, typedi_1.Service)()];
48
48
  let _classDescriptor;
@@ -53,6 +53,16 @@ let DeviceRepository = (() => {
53
53
  this.postgres = (0, db_1.getPostgresClient)();
54
54
  this.axiosInstance = (0, http_utils_1.getDeviceServiceAxiosInstance)();
55
55
  }
56
+ async createDevice(body) {
57
+ try {
58
+ const response = await this.axiosInstance.post(`/devices`, body);
59
+ return response.data;
60
+ }
61
+ catch (error) {
62
+ (0, config_1.getConfig)().LOGGER.error("Failed to create device:", error);
63
+ throw new Error(`Failed to create device: ${error.message || "Unknown error"}`);
64
+ }
65
+ }
56
66
  async getDevice(deviceId, withHubDetails = false) {
57
67
  try {
58
68
  const response = await this.axiosInstance.get(`/devices/${deviceId}?withHubDetails=${withHubDetails} `);
@@ -42,7 +42,7 @@ exports.HubRepository = void 0;
42
42
  const config_1 = require("../../../config/config");
43
43
  const db_1 = require("../../../db");
44
44
  const typedi_1 = require("typedi");
45
- const http_utils_1 = require("../../../utils/http-utils");
45
+ const http_utils_1 = require("../../../utils/http.utils");
46
46
  let HubRepository = (() => {
47
47
  let _classDecorators = [(0, typedi_1.Service)()];
48
48
  let _classDescriptor;
@@ -41,7 +41,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
41
41
  exports.ScheduleRepository = void 0;
42
42
  const typedi_1 = require("typedi");
43
43
  const config_1 = require("../../../config/config");
44
- const http_utils_1 = require("../../../utils/http-utils");
44
+ const http_utils_1 = require("../../../utils/http.utils");
45
45
  let ScheduleRepository = (() => {
46
46
  let _classDecorators = [(0, typedi_1.Service)()];
47
47
  let _classDescriptor;
@@ -3,7 +3,7 @@ export declare class LocalDeviceService {
3
3
  private readonly eventHandler;
4
4
  private readonly deviceRepository;
5
5
  constructor();
6
- createDevice(body: IDevice): Promise<void>;
6
+ createDevice(body: IDevice): Promise<IDevice>;
7
7
  getDevice(deviceId: string, withHubDetails?: boolean): Promise<IDevice>;
8
8
  getDevices(deviceIds: string[], withHubDetails?: boolean): Promise<IDevice[]>;
9
9
  getPropertyDevices(propertyId: string, selectDeviceId?: boolean, type?: string, withHubDetails?: boolean): Promise<IDevice[]>;
@@ -14,7 +14,9 @@ class LocalDeviceService {
14
14
  this.deviceRepository = typedi_1.default.get(Device_repository_1.DeviceRepository);
15
15
  }
16
16
  async createDevice(body) {
17
- return await this.eventHandler.onDeviceCreate(body);
17
+ const device = await this.deviceRepository.createDevice(body);
18
+ await this.eventHandler.onDeviceCreate(device);
19
+ return device;
18
20
  }
19
21
  async getDevice(deviceId, withHubDetails = false) {
20
22
  if (!deviceId) {
@@ -9,7 +9,12 @@ class EventHandler {
9
9
  this.source = "dt-common-device";
10
10
  }
11
11
  async onDeviceCreate(body) {
12
- await dt_pub_sub_1.eventDispatcher.publishEvent(Event_1.DT_EVENT_TYPES.DEVICE.CREATE.SUCCESS, body, this.source);
12
+ // TODO: For Future Consumption
13
+ // await eventDispatcher.publishEvent(
14
+ // DT_EVENT_TYPES.DEVICE.CREATE.SUCCESS,
15
+ // body,
16
+ // this.source
17
+ // );
13
18
  const payload = {
14
19
  eventType: Event_1.DT_EVENT_TYPES.DEVICE.CREATE.SUCCESS,
15
20
  properties: {
package/dist/index.d.ts CHANGED
@@ -7,4 +7,5 @@ export * from "./device/local/interfaces";
7
7
  export * from "./events";
8
8
  export * from "./events/interfaces";
9
9
  export * from "./types";
10
+ export * from "./utils";
10
11
  export { initialize, getConfig, shutdown } from "./config/config";
package/dist/index.js CHANGED
@@ -37,6 +37,8 @@ __exportStar(require("./events"), exports);
37
37
  __exportStar(require("./events/interfaces"), exports);
38
38
  // Types exports
39
39
  __exportStar(require("./types"), exports);
40
+ // Redis utils
41
+ __exportStar(require("./utils"), exports);
40
42
  //initialize export
41
43
  var config_1 = require("./config/config");
42
44
  Object.defineProperty(exports, "initialize", { enumerable: true, get: function () { return config_1.initialize; } });
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Validates if a URL is properly formatted and accessible
3
+ */
4
+ export declare function validateServiceUrl(url: string): boolean;
5
+ /**
6
+ * Creates a properly configured axios instance with error handling
7
+ */
8
+ export declare function createAxiosInstance(baseURL?: string): import("axios").AxiosInstance;
9
+ export declare function getDeviceServiceAxiosInstance(): any;
10
+ /**
11
+ * Retry function for failed HTTP requests
12
+ */
13
+ export declare function retryRequest<T>(requestFn: () => Promise<T>, maxRetries?: number, delay?: number): Promise<T>;
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.validateServiceUrl = validateServiceUrl;
7
+ exports.createAxiosInstance = createAxiosInstance;
8
+ exports.getDeviceServiceAxiosInstance = getDeviceServiceAxiosInstance;
9
+ exports.retryRequest = retryRequest;
10
+ const config_1 = require("../config/config");
11
+ const axios_1 = __importDefault(require("axios"));
12
+ /**
13
+ * Validates if a URL is properly formatted and accessible
14
+ */
15
+ function validateServiceUrl(url) {
16
+ try {
17
+ const parsedUrl = new URL(url);
18
+ return parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:";
19
+ }
20
+ catch (error) {
21
+ (0, config_1.getConfig)().LOGGER.error(`Invalid service URL: ${url}`, error);
22
+ return false;
23
+ }
24
+ }
25
+ /**
26
+ * Creates a properly configured axios instance with error handling
27
+ */
28
+ function createAxiosInstance(baseURL) {
29
+ const instance = axios_1.default.create({
30
+ baseURL,
31
+ timeout: 30000, // 30 seconds timeout
32
+ maxRedirects: 5,
33
+ validateStatus: (status) => status < 500, // Don't throw on 4xx errors
34
+ headers: {
35
+ "Content-Type": "application/json",
36
+ "User-Agent": "dt-common-device/1.3.0",
37
+ },
38
+ });
39
+ // Add request interceptor for logging
40
+ instance.interceptors.request.use((config) => {
41
+ const logger = (0, config_1.getConfig)().LOGGER;
42
+ logger.info(`Making request to: ${config.method?.toUpperCase()} ${config.url}`, {
43
+ baseURL: config.baseURL,
44
+ timeout: config.timeout,
45
+ });
46
+ return config;
47
+ }, (error) => {
48
+ (0, config_1.getConfig)().LOGGER.error("Request interceptor error:", error);
49
+ return Promise.reject(error);
50
+ });
51
+ // Add response interceptor for error handling
52
+ instance.interceptors.response.use((response) => {
53
+ return response;
54
+ }, (error) => {
55
+ const logger = (0, config_1.getConfig)().LOGGER;
56
+ const errorInfo = {
57
+ url: error.config?.url,
58
+ method: error.config?.method,
59
+ status: error.response?.status,
60
+ statusText: error.response?.statusText,
61
+ message: error.message,
62
+ code: error.code,
63
+ baseURL: error.config?.baseURL,
64
+ };
65
+ logger.error("HTTP request failed:", errorInfo);
66
+ // Log additional details for network errors
67
+ if (error.code === "ECONNREFUSED" || error.code === "ENOTFOUND") {
68
+ logger.error("Network connectivity issue detected. Please check:", {
69
+ serviceUrl: error.config?.baseURL,
70
+ errorCode: error.code,
71
+ errorMessage: error.message,
72
+ });
73
+ }
74
+ return Promise.reject(error);
75
+ });
76
+ return instance;
77
+ }
78
+ /**
79
+ * Centralized axios instance for device service
80
+ */
81
+ let deviceServiceAxiosInstance = null;
82
+ function getDeviceServiceAxiosInstance() {
83
+ if (!deviceServiceAxiosInstance) {
84
+ const { DEVICE_SERVICE } = (0, config_1.getConfig)();
85
+ if (!DEVICE_SERVICE) {
86
+ throw new Error("DEVICE_SERVICE is not configured. Call initialize() first with DEVICE_SERVICE.");
87
+ }
88
+ deviceServiceAxiosInstance = createAxiosInstance(DEVICE_SERVICE);
89
+ }
90
+ return deviceServiceAxiosInstance;
91
+ }
92
+ /**
93
+ * Retry function for failed HTTP requests
94
+ */
95
+ async function retryRequest(requestFn, maxRetries = 3, delay = 1000) {
96
+ let lastError;
97
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
98
+ try {
99
+ return await requestFn();
100
+ }
101
+ catch (error) {
102
+ lastError = error;
103
+ if (attempt === maxRetries) {
104
+ (0, config_1.getConfig)().LOGGER.error(`Request failed after ${maxRetries} attempts:`, error);
105
+ throw error;
106
+ }
107
+ (0, config_1.getConfig)().LOGGER.warn(`Request attempt ${attempt} failed, retrying in ${delay}ms:`, {
108
+ error: error.message,
109
+ attempt,
110
+ maxRetries,
111
+ });
112
+ await new Promise((resolve) => setTimeout(resolve, delay));
113
+ delay *= 2; // Exponential backoff
114
+ }
115
+ }
116
+ throw lastError;
117
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./redis.utils";
2
+ export * from "./http.utils";
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./redis.utils"), exports);
18
+ __exportStar(require("./http.utils"), exports);
@@ -0,0 +1,8 @@
1
+ export declare class RedisUtils {
2
+ private client;
3
+ hget(key: string, field: string): Promise<string | null>;
4
+ hset(key: string, field: string, value: string): Promise<number>;
5
+ hdel(key: string, ...fields: string[]): Promise<number>;
6
+ exists(key: string): Promise<number>;
7
+ expire(key: string, seconds: number): Promise<any>;
8
+ }
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
3
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
4
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
5
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
6
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
7
+ var _, done = false;
8
+ for (var i = decorators.length - 1; i >= 0; i--) {
9
+ var context = {};
10
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
11
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
12
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
13
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
14
+ if (kind === "accessor") {
15
+ if (result === void 0) continue;
16
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
17
+ if (_ = accept(result.get)) descriptor.get = _;
18
+ if (_ = accept(result.set)) descriptor.set = _;
19
+ if (_ = accept(result.init)) initializers.unshift(_);
20
+ }
21
+ else if (_ = accept(result)) {
22
+ if (kind === "field") initializers.unshift(_);
23
+ else descriptor[key] = _;
24
+ }
25
+ }
26
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
27
+ done = true;
28
+ };
29
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
30
+ var useValue = arguments.length > 2;
31
+ for (var i = 0; i < initializers.length; i++) {
32
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
33
+ }
34
+ return useValue ? value : void 0;
35
+ };
36
+ var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
37
+ if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
38
+ return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
39
+ };
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.RedisUtils = void 0;
42
+ const typedi_1 = require("typedi");
43
+ const redis_1 = require("../db/redis");
44
+ let RedisUtils = (() => {
45
+ let _classDecorators = [(0, typedi_1.Service)()];
46
+ let _classDescriptor;
47
+ let _classExtraInitializers = [];
48
+ let _classThis;
49
+ var RedisUtils = _classThis = class {
50
+ constructor() {
51
+ this.client = (0, redis_1.getRedisClient)(); // singleton Redis client instance
52
+ }
53
+ async hget(key, field) {
54
+ try {
55
+ return await this.client.hget(key, field);
56
+ }
57
+ catch (error) {
58
+ console.error(`Error getting value for key ${key}:`, error);
59
+ throw error;
60
+ }
61
+ }
62
+ async hset(key, field, value) {
63
+ try {
64
+ return await this.client.hset(key, field, value);
65
+ }
66
+ catch (error) {
67
+ console.error(`Error setting value for key ${key}:`, error);
68
+ throw error;
69
+ }
70
+ }
71
+ // async del(key: string): Promise<number> {
72
+ // return this.client.del(key);
73
+ // }
74
+ async hdel(key, ...fields) {
75
+ return this.client.hdel(key, ...fields);
76
+ }
77
+ // async get(key: string): Promise<string | null> {
78
+ // try {
79
+ // return await this.client.get(key);
80
+ // } catch (error) {
81
+ // console.error(`Error getting value for key ${key}:`, error);
82
+ // throw error;
83
+ // }
84
+ // }
85
+ /* async set(key: string, value: string): Promise<boolean> {
86
+ try {
87
+ await this.client.set(key, value);
88
+ return true;
89
+ } catch (error) {
90
+ console.error(`Error setting value for key ${key}:`, error);
91
+ throw error;
92
+ }
93
+ } */
94
+ async exists(key) {
95
+ try {
96
+ return this.client.exists(key);
97
+ }
98
+ catch (error) {
99
+ console.error(`Error checking existence for key ${key}:`, error);
100
+ throw error;
101
+ }
102
+ }
103
+ async expire(key, seconds) {
104
+ try {
105
+ return this.client.expire(key, seconds);
106
+ }
107
+ catch (error) {
108
+ console.error(`Error setting expiration for key ${key}:`, error);
109
+ throw error;
110
+ }
111
+ }
112
+ };
113
+ __setFunctionName(_classThis, "RedisUtils");
114
+ (() => {
115
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
116
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
117
+ RedisUtils = _classThis = _classDescriptor.value;
118
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
119
+ __runInitializers(_classThis, _classExtraInitializers);
120
+ })();
121
+ return RedisUtils = _classThis;
122
+ })();
123
+ exports.RedisUtils = RedisUtils;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dt-common-device",
3
- "version": "2.0.0",
3
+ "version": "2.0.2",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "scripts": {
@@ -3,7 +3,7 @@ import { initializeAudit } from "dt-audit-library";
3
3
  import { connectDatabase } from "../db/db";
4
4
  import dotenv from "dotenv";
5
5
  import { InternalEventSubscription } from "../events";
6
- import { validateServiceUrl } from "../utils/http-utils";
6
+ import { validateServiceUrl } from "../utils/http.utils";
7
7
 
8
8
  dotenv.config();
9
9
 
package/src/db/redis.ts CHANGED
@@ -3,6 +3,7 @@ import Redis from "ioredis";
3
3
 
4
4
  let redisClient: Redis | null = null;
5
5
 
6
+ //Singleton pattern to ensure only one Redis client instance is create only once and shared across the application
6
7
  export function getRedisClient() {
7
8
  if (!redisClient) {
8
9
  const { host, port } = getRedisDbHostAndPort();
@@ -33,4 +33,8 @@ export abstract class CloudDevice implements ICloudDevice {
33
33
  async getStatus(connectionId: string, deviceId: string): Promise<string> {
34
34
  throw new Error("Method not implemented in Super Class.");
35
35
  }
36
+
37
+ async toLocalDevice(): Promise<IDevice> {
38
+ return {} as IDevice;
39
+ }
36
40
  }
@@ -3,7 +3,7 @@ import { getConfig } from "../../../config/config";
3
3
  import { getPostgresClient } from "../../../db";
4
4
  import { Service } from "typedi";
5
5
  import { IDtDevice } from "../interfaces/IDtDevice";
6
- import { getDeviceServiceAxiosInstance } from "../../../utils/http-utils";
6
+ import { getDeviceServiceAxiosInstance } from "../../../utils/http.utils";
7
7
 
8
8
  @Service()
9
9
  export class DeviceRepository {
@@ -15,6 +15,18 @@ export class DeviceRepository {
15
15
  this.axiosInstance = getDeviceServiceAxiosInstance();
16
16
  }
17
17
 
18
+ async createDevice(body: IDevice): Promise<IDevice> {
19
+ try {
20
+ const response = await this.axiosInstance.post(`/devices`, body);
21
+ return response.data;
22
+ } catch (error: any) {
23
+ getConfig().LOGGER.error("Failed to create device:", error);
24
+ throw new Error(
25
+ `Failed to create device: ${error.message || "Unknown error"}`
26
+ );
27
+ }
28
+ }
29
+
18
30
  async getDevice(
19
31
  deviceId: string,
20
32
  withHubDetails: boolean = false
@@ -2,7 +2,7 @@ import { getConfig } from "../../../config/config";
2
2
  import { getPostgresClient } from "../../../db";
3
3
  import { Service } from "typedi";
4
4
  import { IDevice } from "../interfaces";
5
- import { getDeviceServiceAxiosInstance } from "../../../utils/http-utils";
5
+ import { getDeviceServiceAxiosInstance } from "../../../utils/http.utils";
6
6
 
7
7
  @Service()
8
8
  export class HubRepository {
@@ -1,7 +1,7 @@
1
1
  import { Service } from "typedi";
2
2
  import { getConfig } from "../../../config/config";
3
3
  import { ISchedule } from "../interfaces/ISchedule";
4
- import { getDeviceServiceAxiosInstance } from "../../../utils/http-utils";
4
+ import { getDeviceServiceAxiosInstance } from "../../../utils/http.utils";
5
5
 
6
6
  @Service()
7
7
  export class ScheduleRepository {
@@ -12,8 +12,10 @@ export class LocalDeviceService {
12
12
  this.deviceRepository = Container.get(DeviceRepository);
13
13
  }
14
14
 
15
- async createDevice(body: IDevice): Promise<void> {
16
- return await this.eventHandler.onDeviceCreate(body);
15
+ async createDevice(body: IDevice): Promise<IDevice> {
16
+ const device = await this.deviceRepository.createDevice(body);
17
+ await this.eventHandler.onDeviceCreate(device);
18
+ return device;
17
19
  }
18
20
 
19
21
  async getDevice(
@@ -9,11 +9,12 @@ export class EventHandler {
9
9
  }
10
10
 
11
11
  async onDeviceCreate(body: any) {
12
- await eventDispatcher.publishEvent(
13
- DT_EVENT_TYPES.DEVICE.CREATE.SUCCESS,
14
- body,
15
- this.source
16
- );
12
+ // TODO: For Future Consumption
13
+ // await eventDispatcher.publishEvent(
14
+ // DT_EVENT_TYPES.DEVICE.CREATE.SUCCESS,
15
+ // body,
16
+ // this.source
17
+ // );
17
18
  const payload = {
18
19
  eventType: DT_EVENT_TYPES.DEVICE.CREATE.SUCCESS,
19
20
  properties: {
package/src/index.ts CHANGED
@@ -27,5 +27,8 @@ export * from "./events/interfaces";
27
27
  // Types exports
28
28
  export * from "./types";
29
29
 
30
+ // Redis utils
31
+ export * from "./utils";
32
+
30
33
  //initialize export
31
34
  export { initialize, getConfig, shutdown } from "./config/config";
@@ -0,0 +1,2 @@
1
+ export * from "./redis.utils";
2
+ export * from "./http.utils";
@@ -0,0 +1,70 @@
1
+ import { Service } from "typedi";
2
+ import { getRedisClient } from "../db/redis";
3
+
4
+ @Service()
5
+ export class RedisUtils {
6
+ private client = getRedisClient(); // singleton Redis client instance
7
+
8
+ async hget(key: string, field: string): Promise<string | null> {
9
+ try {
10
+ return await this.client.hget(key, field);
11
+ } catch (error) {
12
+ console.error(`Error getting value for key ${key}:`, error);
13
+ throw error;
14
+ }
15
+ }
16
+
17
+ async hset(key: string, field: string, value: string): Promise<number> {
18
+ try {
19
+ return await this.client.hset(key, field, value);
20
+ } catch (error) {
21
+ console.error(`Error setting value for key ${key}:`, error);
22
+ throw error;
23
+ }
24
+ }
25
+
26
+ // async del(key: string): Promise<number> {
27
+ // return this.client.del(key);
28
+ // }
29
+
30
+ async hdel(key: string, ...fields: string[]): Promise<number> {
31
+ return this.client.hdel(key, ...fields);
32
+ }
33
+
34
+ // async get(key: string): Promise<string | null> {
35
+ // try {
36
+ // return await this.client.get(key);
37
+ // } catch (error) {
38
+ // console.error(`Error getting value for key ${key}:`, error);
39
+ // throw error;
40
+ // }
41
+ // }
42
+
43
+ /* async set(key: string, value: string): Promise<boolean> {
44
+ try {
45
+ await this.client.set(key, value);
46
+ return true;
47
+ } catch (error) {
48
+ console.error(`Error setting value for key ${key}:`, error);
49
+ throw error;
50
+ }
51
+ } */
52
+
53
+ async exists(key: string): Promise<number> {
54
+ try {
55
+ return this.client.exists(key);
56
+ } catch (error) {
57
+ console.error(`Error checking existence for key ${key}:`, error);
58
+ throw error;
59
+ }
60
+ }
61
+
62
+ async expire(key: string, seconds: number): Promise<any> {
63
+ try {
64
+ return this.client.expire(key, seconds);
65
+ } catch (error) {
66
+ console.error(`Error setting expiration for key ${key}:`, error);
67
+ throw error;
68
+ }
69
+ }
70
+ }
File without changes