UNPKG

naga-audit-service

Version:

A comprehensive audit service library for NestJS applications with MongoDB support

136 lines 6.48 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AuditService = void 0; const mongoose_1 = require("mongoose"); const common_1 = require("@nestjs/common"); const config_1 = require("@nestjs/config"); const dynamic_schema_constants_1 = require("src/common/constants/dynamic-schema.constants"); const http_client_service_1 = require("src/common/inter-service-communication/http-client.service"); const pagination_service_1 = require("src/common/shared/pagination/pagination.service"); let AuditService = class AuditService { constructor(httpClientService, paginationService, configService) { this.httpClientService = httpClientService; this.paginationService = paginationService; this.configService = configService; this.modelCache = new Map(); this.collectionConfigCache = {}; } getModel(name, schemaDefinition) { if (this.modelCache.has(name)) { return this.modelCache.get(name); } if (mongoose_1.default.connection.readyState !== 1) { throw new Error('Mongoose is not connected to the database yet.'); } const mongooseSchema = new mongoose_1.Schema(schemaDefinition, { timestamps: true, minimize: false, }); const dynamicModel = mongoose_1.models[name] || (0, mongoose_1.model)(name, mongooseSchema); this.modelCache.set(name, dynamicModel); return dynamicModel; } async setCollectionConfigCache() { try { const configResponse = await this.httpClientService.get('NAGA_CONFIG_SERVICE', `/collections-config`); const configList = configResponse?.items || []; if (Array.isArray(configList)) { for (const config of configList) { if (config?.serviceName) { this.collectionConfigCache[config.serviceName] = { collections: config.collections || [], collectionsConfigId: config.collectionsConfigId, }; } } } console.log('Collection Config Cache Set:', this.collectionConfigCache); } catch (err) { console.error('Error fetching collection config:', err); throw new common_1.BadGatewayException('Failed to fetch collection config'); } } async ensureCollectionExists(incomingCollectionName) { if (!incomingCollectionName) { throw new common_1.BadRequestException('collectionName is required'); } if (Object.keys(this.collectionConfigCache).length === 0) { await this.setCollectionConfigCache(); } const found = Object.entries(this.collectionConfigCache).find(([, config]) => config.collections.includes(incomingCollectionName)); if (!found) { throw new common_1.NotFoundException(`Collection "${incomingCollectionName}" not found in any service config`); } } async transformAndInsert(createAuditDto) { if (mongoose_1.default.connection.readyState !== 1) { console.warn('⏳ Waiting for MongoDB connection...'); throw new Error('MongoDB connection not ready. Make sure to call NoukhaAuditLog.configure() first.'); } const { collectionName, ...rest } = createAuditDto; if (!collectionName) { throw new common_1.BadGatewayException('collectionName and serviceName are required'); } await this.ensureCollectionExists(collectionName); const baseData = { prevsState: {}, newState: {}, }; const metaData = {}; for (const key in rest) { if (dynamic_schema_constants_1.DEFAULT_FIELDS.includes(key)) { baseData[key] = rest[key]; } else if (key === 'metaData' && typeof rest[key] === 'object') { Object.assign(metaData, rest[key]); } else { metaData[key] = rest[key]; } } const finalDoc = { ...baseData, metaData }; const AuditModel = this.getModel(collectionName, dynamic_schema_constants_1.BASE_DYNAMIC_SCHEMA); return await new AuditModel(finalDoc).save(); } async getAuditByCollectionName(collectionName, query = {}) { if (!collectionName) { throw new common_1.BadRequestException('Collection name is required'); } if (mongoose_1.default.connection.readyState !== 1) { throw new Error('MongoDB connection not ready. Make sure to call NoukhaAuditLog.configure() first.'); } try { const model = this.getModel(collectionName, dynamic_schema_constants_1.BASE_DYNAMIC_SCHEMA); const paginatedData = await this.paginationService.findAndPaginate(model, collectionName, { skip: query.skip, limit: query.limit, filter: query.filter, projection: query.projection, sort: query.sort, }); return paginatedData; } catch (error) { console.error('Error while fetching audit data:', error); throw new common_1.BadGatewayException('Failed to fetch audit data'); } } }; exports.AuditService = AuditService; exports.AuditService = AuditService = __decorate([ (0, common_1.Injectable)(), __metadata("design:paramtypes", [http_client_service_1.HttpClientService, pagination_service_1.PaginationService, config_1.ConfigService]) ], AuditService); //# sourceMappingURL=audit.service.js.map