import { HttpClient } from '@angular/common/http'; import { inject, Injectable } from '@angular/core'; import type { Bundle, CodeableConcept, Extension, FhirResource, Patient } from 'fhir/r4'; import { firstValueFrom } from 'rxjs'; import { ApiConfiguration } from './api/api-configuration'; export const CURP = 'https://isssteleon.org/fhir/sid/curp'; export const EXT = 'https://isssteleon.org/fhir/StructureDefinition/'; export type Params = Record; @Injectable({ providedIn: 'root' }) export class Fhir { private readonly http = inject(HttpClient); private readonly root = inject(ApiConfiguration).rootUrl; read(domain: string, type: T['resourceType'], id: string): Promise { return firstValueFrom(this.http.get(`${this.root}/${domain}/fhir/${type}/${id}`)); } search(domain: string, type: string, params: Params = {}): Promise { const query = Object.fromEntries( Object.entries(params).filter(([, v]) => v !== undefined), ) as Record; return firstValueFrom( this.http.get(`${this.root}/${domain}/fhir/${type}`, { params: query }), ); } follow(domain: string, bundle: Bundle, relation: 'next' | 'previous'): Promise | null { const link = bundle.link?.find((l) => l.relation === relation)?.url; if (!link) return null; const url = new URL(link); const type = url.pathname.split('/').pop(); return firstValueFrom( this.http.get(`${this.root}/${domain}/fhir/${type}${url.search}`), ); } async all(domain: string, type: string, params: Params = {}): Promise { const pages = [await this.search(domain, type, params)]; for (let next = this.follow(domain, pages[0], 'next'); next;) { const page = await next; pages.push(page); next = this.follow(domain, page, 'next'); } return pages; } } export function resources( bundles: Bundle | Bundle[], type: T['resourceType'], mode?: 'match' | 'include', ): T[] { return [bundles] .flat() .flatMap((b) => b.entry ?? []) .filter((e) => e.resource?.resourceType === type && (!mode || e.search?.mode === mode)) .map((e) => e.resource as T); } export function ext( element: { extension?: Extension[] } | undefined, name: string, ): Extension | undefined { return element?.extension?.find((e) => e.url === EXT + name); } export function code(concept: CodeableConcept | undefined): string | undefined { return concept?.coding?.[0]?.code; } export function label(concept: CodeableConcept | undefined): string { return concept?.text ?? concept?.coding?.[0]?.display ?? concept?.coding?.[0]?.code ?? ''; } export function patientName(patient: Patient | undefined): string | undefined { return patient?.name?.[0]?.text; } export function patientCurp(patient: Patient | undefined): string | undefined { return patient?.identifier?.find((i) => i.system === CURP)?.value; } export function extensions(element: { extension?: Extension[] }, name: string): Extension[] { return (element.extension ?? []).filter((e) => e.url === EXT + name); }