import { Injectable } from '@nestjs/common' import { isNil } from 'lodash' import { plainToClass } from 'class-transformer' import { Patient } from '../../models' import { RedisService } from '../redis/redis.service' import { PatientRepository } from '../../repositories' export type PatientCacheValue = Patient & { error: string } export const ERROR_PATIENT_NOT_FOUND = 'not-found' @Injectable() export class PatientService { constructor(private readonly patientRepository: PatientRepository, private readonly redis: RedisService) {} async getPatientCache(login: string): Promise> { const cache = await this.redis.get(`patient:${login}`) const patientCached: PatientCacheValue = cache && JSON.parse(cache) if (isNil(patientCached)) return null if (patientCached?.error === ERROR_PATIENT_NOT_FOUND) return null if (!patientCached) return {} return patientCached } async createPatientCache(patient: Patient): Promise { const patientFull = plainToClass(Patient, patient) const patientToCache = await this.findPatientForCache(patientFull) await this.setCache(`patient:${patientFull.login}`, patientToCache || {}) } private async findPatientForCache(patient: Patient): Promise> { const patientToCache = await this.patientRepository.findByLogin(patient.login) if (patientToCache == null) return null return this.buildPatientToCache(patientToCache) } private async setCache(cacheKey: string, patient: Partial): Promise { await this.redis.set(cacheKey, JSON.stringify(patient)) } private buildPatientToCache = (patient: Patient): Partial => { return { id: patient.id, name: patient.name, email: patient.email, document_number: patient.document_number, height: patient.height, weight: patient.weight, subscriber: patient.subscriber, teleconsultations_credit: patient.teleconsultations_credit, sign_up_at: patient.sign_up_at, } } }