UNPKG

dt-common-device

Version:

A secure and robust device management library for IoT applications

309 lines (308 loc) 15.9 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); var _, done = false; for (var i = decorators.length - 1; i >= 0; i--) { var context = {}; for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { if (result === void 0) continue; if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; if (_ = accept(result.init)) initializers.unshift(_); } else if (_ = accept(result)) { if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; }; var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i = 0; i < initializers.length; i++) { value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } return useValue ? value : void 0; }; var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) { if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AdminService = void 0; const typedi_1 = __importStar(require("typedi")); const Admin_repository_1 = require("./Admin.repository"); const redis_utils_1 = require("../../utils/redis.utils"); let AdminService = (() => { let _classDecorators = [(0, typedi_1.Service)()]; let _classDescriptor; let _classExtraInitializers = []; let _classThis; var AdminService = _classThis = class { constructor() { this.adminRepository = typedi_1.default.get(Admin_repository_1.AdminRepository); this.redisUtils = typedi_1.default.get(redis_utils_1.RedisUtils); } async getZonesByAccessGroupIds(accessGroupIds, propertyId) { try { return await this.adminRepository.getZonesByAccessGroupIds(accessGroupIds, propertyId); } catch (error) { console.log(error); return []; } } async getZonesByAccessGroups(accessGroupIds, type) { try { return await this.adminRepository.getZonesByAccessGroups(accessGroupIds, type); } catch (error) { return []; } } async getAccessGroup(accessGroupId, propertyId) { if (!accessGroupId) { throw new Error("Access Group ID is required"); } let accessGroup; const redisKey = `collection:${accessGroupId}`; accessGroup = await this.redisUtils.hget(redisKey, accessGroupId); if (accessGroup) return accessGroup; accessGroup = await this.adminRepository.getAccessGroup(accessGroupId, propertyId); if (!accessGroup) return null; await this.redisUtils.hsetWithTTL(redisKey, accessGroup?.id, JSON.stringify(accessGroup), 86400); await this.redisUtils.sadd(`property_collections:${accessGroup?.propertyId}`, accessGroup?.id); return accessGroup; } async getAccessGroupByZoneId(zoneId) { if (!zoneId) { throw new Error("Zone ID is required"); } const zoneAccessGroups = await this.adminRepository.getZoneAccessGroupByZoneId(zoneId); if (!zoneAccessGroups?.length) return []; const accessGroups = []; for (const zoneAccessGroup of zoneAccessGroups) { const accessGroup = await this.adminRepository.getAccessGroup(zoneAccessGroup.collectionId); if (accessGroup) accessGroups.push(accessGroup); } return accessGroups; } //--------------------------USED FOR QUERY RESERVATION----------------------- async getAccessgroupBySubParentZoneId(zoneId) { if (!zoneId) { throw new Error("Zone ID is required"); } try { // Get the zone to retrieve propertyId if needed const zone = await this.adminRepository.getZone(zoneId); if (!zone) { return []; } // Use Map to collect unique access groups (by ID) const accessGroupsMap = new Map(); // Track visited zones to avoid cycles and duplicate checks const visitedZoneIds = new Set(); // OPTIMIZATION: Set to true if you only need to check if ANY access group exists // Set to false if you need ALL access groups from entire hierarchy const stopOnFirstFound = true; // Recursive function to traverse hierarchy and collect access groups const traverseZoneHierarchy = async (currentZoneId, propertyId) => { // Base case 1: if zone already visited, return (prevents cycles) if (visitedZoneIds.has(currentZoneId)) { return false; } // Base case 2: early exit if we found access group and only need existence check if (stopOnFirstFound && accessGroupsMap.size > 0) { return true; } // Mark as visited visitedZoneIds.add(currentZoneId); // Check access groups for current zone (query as we traverse) const zoneAccessGroups = await this.adminRepository.getAccessGroupsByZoneId(currentZoneId); // If we found access groups, add to map if (zoneAccessGroups.length > 0) { zoneAccessGroups.forEach((ag) => accessGroupsMap.set(ag.id, ag)); // Early exit optimization: if we only need to know if access group exists if (stopOnFirstFound) { return true; // Stop traversal - we found what we need } } // Get current zone details const currentZone = await this.adminRepository.getZone(currentZoneId); if (!currentZone) { return false; } // Recursive case 1: Traverse up to parent zone (if exists and not visited) if (currentZone.parentId && !visitedZoneIds.has(currentZone.parentId)) { const found = await traverseZoneHierarchy(currentZone.parentId, propertyId); // Early exit: if we found access group in parent, stop checking children if (found && stopOnFirstFound) { return true; } } // Recursive case 2: Traverse down to direct child zones only // Only check children if we haven't found an access group yet (optimization) if (!stopOnFirstFound || accessGroupsMap.size === 0) { const directChildZoneIds = await this.adminRepository.getDirectChildZones(currentZoneId, propertyId); // Recursively process each direct child zone for (const childZoneId of directChildZoneIds) { if (!visitedZoneIds.has(childZoneId)) { const found = await traverseZoneHierarchy(childZoneId, propertyId); // Early exit: if we found access group in any child, we can stop if (found && stopOnFirstFound) { return true; } } } } return accessGroupsMap.size > 0; }; // Start recursive traversal from the given zone await traverseZoneHierarchy(zoneId, zone.propertyId); return Array.from(accessGroupsMap.values()); } catch (error) { console.error("Error in getAccessgroupBySubParentZoneId:", error); return []; } } // used for query reservation to find all the zones mapped with the access groups async getAllParentSubZonesByAccessGroupIds(accessGroupIds) { if (!accessGroupIds || accessGroupIds.length === 0) { throw new Error("Access Group IDs are required"); } try { // Step 1: Find all zones mapped with these access groups const mappedZoneIds = await this.adminRepository.getZoneIdsByAccessGroupIds(accessGroupIds); if (mappedZoneIds.length === 0) { return []; } // OPTIMIZATION 1: Batch get all zones at once (reduces DB calls from O(n) to O(1)) const zones = await this.adminRepository.getZonesByIds(mappedZoneIds); const zoneMap = new Map(); zones.forEach((zone) => zoneMap.set(zone.id, zone)); // Use Set to collect unique zone IDs from the start const allZoneIds = new Set(mappedZoneIds); // OPTIMIZATION 2: Process all zones in parallel (reduces time from O(n) sequential to O(1) parallel) const zoneProcessingPromises = mappedZoneIds.map(async (zoneId) => { const zone = zoneMap.get(zoneId); if (!zone) { return { parentIds: [], childIds: [] }; } // OPTIMIZATION 3: Get parents and children in parallel for each zone const [parentZoneIds, childZoneIds] = await Promise.all([ this.adminRepository.getAllParentZones(zoneId), this.adminRepository.getAllChildZones(zoneId, zone.propertyId), ]); return { parentIds: parentZoneIds, childIds: childZoneIds }; }); // Wait for all zone processing to complete const results = await Promise.all(zoneProcessingPromises); // OPTIMIZATION 4: Batch add all IDs to Set (O(n) operation) results.forEach(({ parentIds, childIds }) => { parentIds.forEach((id) => allZoneIds.add(id)); childIds.forEach((id) => allZoneIds.add(id)); }); return Array.from(allZoneIds); } catch (error) { console.error("Error in getAllParentSubZonesByAccessGroupIds:", error); return []; } } //---------------------------------------------------------------------------------- async getZone(zoneId, propertyId) { if (!zoneId) { throw new Error("Zone ID is required"); } const cachedZone = await this.redisUtils.get(`zone:${zoneId}`); if (cachedZone) return JSON.parse(cachedZone); const zone = await this.adminRepository.getZone(zoneId, propertyId); if (!zone) return null; await this.redisUtils.set(`zone:${zoneId}`, JSON.stringify(zone), 86400); return zone; } async getUser(userId) { if (!userId) { throw new Error("User ID is required"); } const user = await this.adminRepository.getUser(userId); if (!user) return null; return user; } async getZoneByDeviceId(deviceId) { if (!deviceId) { throw new Error("Device ID is required"); } const zone = await this.adminRepository.getZoneByDeviceId(deviceId); if (!zone) return null; return zone; } async getAccessGroups(propertyId, accessibleBy) { if (!propertyId) { throw new Error("Property ID is required"); } return await this.adminRepository.getAccessGroups(propertyId, accessibleBy); } }; __setFunctionName(_classThis, "AdminService"); (() => { const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); AdminService = _classThis = _classDescriptor.value; if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); __runInitializers(_classThis, _classExtraInitializers); })(); return AdminService = _classThis; })(); exports.AdminService = AdminService;