UNPKG

mongodb-dynamic-api

Version:

Auto generated CRUD API for MongoDB using NestJS

49 lines 2.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseAggregateService = void 0; const mongodb_pipeline_builder_1 = require("mongodb-pipeline-builder"); const services_1 = require("../../services"); class BaseAggregateService extends services_1.BaseService { constructor(model) { super(model); this.model = model; } async aggregate(pipeline) { try { let documents; let count; let totalPage; if (this.withPagination(pipeline)) { const pagingResult = await (0, mongodb_pipeline_builder_1.GetPagingResult)(this.model, pipeline); documents = pagingResult.GetDocs(); count = pagingResult.GetCount(); totalPage = pagingResult.GetTotalPageNumber(); } else { const result = await (0, mongodb_pipeline_builder_1.GetResult)(this.model, pipeline); documents = result.GetDocs(); count = result.GetCount(); totalPage = 1; } if (this.callback && documents.length) { await Promise.all(documents.map((document) => this.callback(this.addDocumentId(document), this.callbackMethods))); } return { list: documents.map((d) => this.buildInstance(d)), count, totalPage }; } catch (error) { this.handleMongoErrors(error, false); this.handleDuplicateKeyError(error); } } withPagination(pipeline) { const firstStageFacet = pipeline[0].$facet; if (!firstStageFacet) { return false; } const hasValidDocs = Array.isArray(firstStageFacet.docs) && firstStageFacet.docs.length > 0; const hasValidCount = Array.isArray(firstStageFacet.count) && firstStageFacet.count.length > 0; return hasValidDocs && hasValidCount; } } exports.BaseAggregateService = BaseAggregateService; //# sourceMappingURL=base-aggregate.service.js.map