Skip to content
Snippets Groups Projects
structures.service.ts 1.49 KiB
Newer Older
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 { 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>) {}

  async create(createStructrureDto: CreateStructureDto): Promise<Structure> {
    const createdStructure = new this.structureModel(createStructrureDto);
    return createdStructure.save();
  }

Hugo SUBTIL's avatar
Hugo SUBTIL committed
  async search(searchString: string): Promise<Structure[]> {
    return this.structureModel.find({ $text: { $search: searchString } }).exec();
  }

  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'}]
   */
  async countByStructureKey(key: string): Promise<any> {
    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(),
        };
      })
    );
  }

  async countByEquipmentsKey(key: string): Promise<any> {
    return [{ id: key, count: await this.structureModel.countDocuments({ [key]: true }).exec() }];
  }