Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
2.8 kB
4
Indexable
Never
public list = async (filters: IStructureQuery = {}) => {

    const paging = (filters.pageNumber && filters.nPerPage) ? true : false

    const pageNumber = filters.pageNumber ? (parseInt(filters.pageNumber)) : 1
    delete filters.pageNumber
    const nPerPage = filters.nPerPage ? (parseInt(filters.nPerPage)) : 10
    delete filters.nPerPage
    if (filters.parent === IS_EMPTY) delete filters.parent

    let select = 'id name description config.objective config.bibliography config.observation structure_category_id'
    if (filters.select) {
      select = filters.select
      delete filters.select
    }

    let aux = false;
    if (filters.aux) {
      aux = true
      delete filters.aux
    }

    // let where = filters
    let where = {}
    if (filters.config) where["config"] = filters.config
    if (filters.alliance_id) where['alliance_id'] = filters.alliance_id
    if (filters.parent) where['parent'] = filters.parent

    const structureCategories = await StructureCategory.findOne({ alliance_id: filters.alliance_id, name: 'Grupo academico' })

    if (!structureCategories) return responseUtility.buildResponseFailed('json')

    where['structure_category_id'] = structureCategories._id


    if (filters.user_id) delete filters.user_id

    if (filters.search) {
      const search = filters.search
      where = {
        ...where,
        $or: [
          { name: { $regex: '.*' + search + '.*', $options: 'i' } },
          { description: { $regex: '.*' + search + '.*', $options: 'i' } },
        ]
      }
    } else {
      delete filters.search
    }

    let registers = []
    try {
      if (aux) {
        registers = await Structure.find(where)
          .select(select)
          .populate({
            path: 'parent', select: 'name',
            populate: { path: 'structure_category_id', select: 'name' },
          })

          .skip(paging ? (pageNumber > 0 ? ((pageNumber - 1) * nPerPage) : 0) : null)
          .limit(paging ? nPerPage : null)

        registers.map(async (r, i) => {
          if (r.config.teacher) {
            registers[i].config.teacher.profile.avatar = await userService.avatarUrl(r.config.teacher)
          }
        })
      } else {
        registers = await Structure.find(where)
          .select(select)
          .populate('structure_category_id')

          .skip(paging ? (pageNumber > 0 ? ((pageNumber - 1) * nPerPage) : 0) : null)
          .limit(paging ? nPerPage : null)

      }



    } catch (e) {
      return responseUtility.buildResponseFailed('json')

    }

    return responseUtility.buildResponseSuccess('json', null, {
      additional_parameters: {
        Structure: [
          ...registers
        ],
        total_register: await Structure.find(filters).countDocuments(),
        pageNumber: pageNumber,
        nPerPage: nPerPage
      }
    })
  }