import { Injectable } from '@nestjs/common' import { isNil } from 'lodash' import { AnthropometryRepository } from '../../repositories/anthropometry.repository' import { Anthropometry, Patient } from '../../models' import { RedisService } from '../redis/redis.service' import { AnthropometriesFilter, PatientRepository } from '../../repositories' export type CacheValue = Anthropometry[] & { error: string }[] export const ERROR_NOT_FOUND = 'not-found' @Injectable() export class BioimpedanceService { constructor( private readonly anthropometryRepository: AnthropometryRepository, private readonly patientRepository: PatientRepository, private readonly redis: RedisService, ) {} async getPatientAnthropometriesCache(patient: Patient, filter: AnthropometriesFilter): Promise { const cache = await this.redis.get(patient.login + '-' + filter) const anthropometries: CacheValue = cache && JSON.parse(cache) if (isNil(anthropometries)) return null if (anthropometries?.[0]?.error === ERROR_NOT_FOUND) return null if (!Array.isArray(anthropometries)) return [] return anthropometries } async createPatientAnthropometriesCache(patientId: string, filter: AnthropometriesFilter): Promise { const patient = await this.patientRepository.get(patientId) const anthropometries = await this.findAnthropometriesForCache(patient, filter) await this.setCache(patient.login + '-' + filter, anthropometries) } private async findAnthropometriesForCache( patient: Patient, filter: AnthropometriesFilter, ): Promise[]> { const patientWithAnthropometries = await this.anthropometryRepository.findByPatientLogin(patient.login, filter) return this.buildAnthropometriesToCache(patientWithAnthropometries, patientWithAnthropometries?.anthropometries) } private async setCache(cacheKey: string, anthropometries: Partial[]): Promise { await this.redis.set(cacheKey, JSON.stringify(anthropometries)) } private buildAnthropometriesToCache = ( patient: Patient, anthropometries: Anthropometry[], ): Partial[] => anthropometries?.map((anthropometry: Anthropometry, index: number) => { const data = anthropometry.toPlain() const isLast = index === anthropometries.length - 1 data.subscriber = patient.subscriber data.allow_bioimpedance = patient.subscriber || isLast return data }) || [] }