import { Injectable } from '@nestjs/common' import { isEmpty, omit } from 'lodash' import { endOfDay, startOfDay } from 'date-fns' import { Competition } from '../../../models' import { BaseRepository } from '../../base.repository' import { CountryHelper, LanguageCountryCode } from '../../../utils/countries' import { HttpService } from '../../../services/http' const ATTRIBUTES = ` id title category patient_id winner_id link created_at finished_at will_end_at cancelled_at winner { id score position } competition_category { value description measure_type } ` const INSERT = ` mutation insert($object: competition_insert_input!) { object: insert_competition_one(object: $object) { ${ATTRIBUTES} } } ` const GET = ` query get($id: uuid!) { result: competition(where: {id: {_eq: $id}}) { ${ATTRIBUTES} } } ` const GET_ALL_UNFINISHED = ` query get($patientId: String!) { result: competition(where: {competitors: {patient_id: {_eq: $patientId}}, finished_at: {_is_null: true}}) { ${ATTRIBUTES} competitors(where: {patient_id: {_eq: $patientId}}) { id patient_id position history(order_by: {created_at: desc}) { id done_at value score position } } } } ` const GET_ALL_WILL_END_AT = ` query get($_gte: timestamptz!, $_lte: timestamptz!) { result: competition(where: {will_end_at: {_gte: $_gte, _lte: $_lte}}) { ${ATTRIBUTES} competitors(order_by: {position: asc}) { patient_id position } } } ` @Injectable() export class CompetitionRepository extends BaseRepository { constructor(protected readonly httpService: HttpService) { super(httpService, 'competition') } async create(object: Competition, options?: { language?: LanguageCountryCode }): Promise { const qv = { object: omit(object.toPlain(), ['competitors']) } const { data } = await this.fetchGraphQL({ body: { query: INSERT, variables: qv }, ...(options?.language ? { language: CountryHelper.extractOnlyLanguage(options?.language) } : {}), }) return Competition.toInstance({ ...object.toPlain(), ...data.object }) } async get(id: string, options?: { language?: LanguageCountryCode }): Promise { const { data } = await this.fetchGraphQL({ body: { query: GET, variables: { id } }, ...(options?.language ? { language: CountryHelper.extractOnlyLanguage(options?.language) } : {}), }) return isEmpty(data.result) ? null : Competition.toInstance(data.result[0]) } async getAllUnfinished(patientId: string): Promise { const { data } = await this.fetchGraphQL({ body: { query: GET_ALL_UNFINISHED, variables: { patientId } }, }) return isEmpty(data.result) ? [] : data.result.map(row => Competition.toInstance(row)) } async getAllWillEndAt(date: Date): Promise { console.log({ query: GET_ALL_WILL_END_AT, variables: { _gte: startOfDay(date), _lte: endOfDay(date) } }) const { data } = await this.fetchGraphQL({ body: { query: GET_ALL_WILL_END_AT, variables: { _gte: startOfDay(date), _lte: endOfDay(date) } }, }) return isEmpty(data.result) ? [] : data.result.map(row => Competition.toInstance(row)) } }