All files / src/infrastructure/database/repositories cached-vaccine.repository.ts

100% Statements 15/15
87.5% Branches 7/8
100% Functions 4/4
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60          23x 23x                                   851x                 71x 71x       32x   32x 27x 27x 26x       6x 6x 5x     6x       11x      
import { VaccineRepository } from '../../../application/vaccine/vaccine-repository';
import { Vaccine } from '../../../domain/vaccine/vaccine';
import { ACTIVE_VACCINE_CATALOG } from '../../../shared/config/vaccine-catalog';
import { CacheClient } from '../../cache/cache-client';
 
export const VACCINE_CATALOG_CACHE_KEY = `vaccines:catalog:${ACTIVE_VACCINE_CATALOG.version}`;
const CATALOG_CACHE_TTL_SECONDS = 3600;
 
interface CachedVaccineProps {
  id: string;
  code: string;
  name: string;
  description: string;
  guidance: string | null;
  recommendedAgeInMonths: number;
  doseNumber: number;
  recommendationKind: 'ROUTINE' | 'CONDITIONAL' | 'RECURRING';
  scheduleVersion: string;
  effectiveFrom: string;
  effectiveTo: string | null;
  isActive: boolean;
}
 
function fromCachedProps(props: CachedVaccineProps): Vaccine {
  return Vaccine.create({
    ...props,
    effectiveFrom: new Date(props.effectiveFrom),
    effectiveTo: props.effectiveTo ? new Date(props.effectiveTo) : null,
  });
}
 
export class CachedVaccineRepository implements VaccineRepository {
  constructor(
    private readonly inner: VaccineRepository,
    private readonly cache: CacheClient,
  ) {}
 
  async findAll(): Promise<Vaccine[]> {
    const cached = await this.cache.get(VACCINE_CATALOG_CACHE_KEY);
 
    if (cached) {
      const props = JSON.parse(cached) as CachedVaccineProps[];
      if (props.length > 0) {
        return props.map(fromCachedProps);
      }
    }
 
    const vaccines = await this.inner.findAll();
    if (vaccines.length > 0) {
      await this.cache.set(VACCINE_CATALOG_CACHE_KEY, JSON.stringify(vaccines), 'EX', CATALOG_CACHE_TTL_SECONDS);
    }
 
    return vaccines;
  }
 
  findById(id: string): Promise<Vaccine | null> {
    return this.inner.findById(id);
  }
}