import { Injectable } from '@nestjs/common' import { isEmpty } from 'lodash' import { plainToClass } from 'class-transformer' import { CountryHelper, LanguageCountryCode } from '../utils/countries' import { SmartfitUnit } from '../models' import { HttpService } from '../services/http' import { BaseRepository } from './base.repository' const ATTRIBUTES = ` id name acronym country_code city state address allow_offline allow_teacher_indication ` const FIND_BY_ACRONYM = ` query smartfit_unit_by_acronym($acronym: String!) { smartfit_unit(where: {acronym: {_eq: $acronym}}, limit: 1) { ${ATTRIBUTES} } } ` const GET = ` query smartfit_unit($id: Int!) { smartfit_unit(where: {id: {_eq: $id}}, limit: 1) { ${ATTRIBUTES} } } ` const ALL = ` query smartfit_unit($countryCode: [String!]!) { smartfit_unit(where: {country_code: {_in: $countryCode} }) { ${ATTRIBUTES} } } ` @Injectable() export class SmartfitUnitRepository extends BaseRepository { constructor(protected readonly httpService: HttpService) { super(httpService, 'smartfit_unit') } async get(id: number): Promise { const { data } = await this.fetchGraphQL({ body: { query: GET, variables: { id } }, }) return isEmpty(data.smartfit_unit) ? null : plainToClass(SmartfitUnit, data.smartfit_unit[0]) } async findByAcronym(acronym: string): Promise { const { data } = await this.fetchGraphQL({ body: { query: FIND_BY_ACRONYM, variables: { acronym } }, }) return isEmpty(data.smartfit_unit) ? null : plainToClass(SmartfitUnit, data.smartfit_unit[0]) } async all(countryCode?: LanguageCountryCode): Promise> { const { data } = await this.fetchGraphQL({ body: { query: ALL, variables: { countryCode: countryCode ? [CountryHelper.extractOnlyCountryCode(countryCode)] : Object.values(LanguageCountryCode).map(langagueCountryCode => CountryHelper.extractOnlyCountryCode(langagueCountryCode), ), }, }, }) return isEmpty(data.smartfit_unit) ? [] : data.smartfit_unit.map(value => plainToClass(SmartfitUnit, value)) } }