Skip to content
Snippets Groups Projects
structures.service.ts 2.21 KiB
Newer Older
  • Learn to ignore specific revisions
  • Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    import { Injectable } from '@nestjs/common';
    
    import { InjectModel } from '@nestjs/mongoose';
    import { Model } from 'mongoose';
    import { CreateStructureDto } from './dto/create-structure.dto';
    
    import { Filter } from './schemas/filter.schema';
    
    import { Structure, StructureDocument } from './schemas/structure.schema';
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    
    @Injectable()
    
    export class StructuresService {
      constructor(@InjectModel(Structure.name) private structureModel: Model<StructureDocument>) {}
    
    
      public async create(createStructrureDto: CreateStructureDto): Promise<Structure> {
    
        const createdStructure = new this.structureModel(createStructrureDto);
        return createdStructure.save();
      }
    
    
      public async search(searchString: string, filters?: Array<any>): Promise<Structure[]> {
        let query: any;
        if (searchString && filters) {
          query = [...this.parseFilter(filters), { $text: { $search: searchString } }];
        } else if (filters) {
          query = this.parseFilter(filters);
        } else {
          query = [{ $text: { $search: searchString } }];
        }
        return this.structureModel.find({ $and: query }).exec();
    
      /**
       * Parse filter value from string to boolean
       * @param filters
       */
      private parseFilter(filters: Array<any>): Array<any> {
        return filters.map((filter) => {
          const key = Object.keys(filter)[0];
          if (filter[key] === 'True') {
            return { [key]: true };
          } else {
            return filter;
          }
        });
      }
    
      public async findAll(): Promise<Structure[]> {
    
        return this.structureModel.find().exec();
      }
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    
      /**
       * Count every value occurence of a given key
       * @param key structure key
       * @return [{id: 'key', count: 'value'}]
       */
    
      public async countByStructureKey(key: string): Promise<any> {
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        const uniqueElements = await this.structureModel.distinct(key).exec();
        return await Promise.all(
          uniqueElements.map(async (value) => {
            return {
              id: value,
              count: await this.structureModel.countDocuments({ [key]: { $elemMatch: { $eq: value } } }).exec(),
            };
          })
        );
      }
    
    
      public async countByEquipmentsKey(key: string, displayKey: string): Promise<any> {
        return [{ id: displayKey, count: await this.structureModel.countDocuments({ [key]: true }).exec() }];