69 lines
2.5 KiB
JavaScript
69 lines
2.5 KiB
JavaScript
const createError = require('http-errors');
|
|
const config = require('../config');
|
|
const { getBusToken } = require('../utils/busAuth');
|
|
const { getPatientById, searchPatient } = require('../services/patient');
|
|
const { searchDocumentReferenceByPatient } = require('../services/documentReference');
|
|
|
|
const NATIONAL_ID_SYSTEM = 'https://federador.msal.gob.ar/patient-id';
|
|
|
|
/**
|
|
* Extracts the Federador national identifier from a Patient resource.
|
|
*/
|
|
function extractNationalIdentifier(patient) {
|
|
const identifiers = Array.isArray(patient.identifier) ? patient.identifier : [];
|
|
return identifiers.find(id => id.system === NATIONAL_ID_SYSTEM) || null;
|
|
}
|
|
|
|
async function getPatient(token, identifier) {
|
|
const response = await searchPatient(token, { identifier: identifier });
|
|
return Promise.resolve(response.data.entry[0].fullUrl);
|
|
}
|
|
|
|
async function getDocumentReferencesForPatient(token, patient) {
|
|
const response = await searchDocumentReferenceByPatient(token, patient)
|
|
return Promise.resolve(response.data);
|
|
}
|
|
/**
|
|
* ITI-67: Find Document References (MHD)
|
|
*
|
|
* GET /fhir/DocumentReference?subject=:localId
|
|
*
|
|
* Flow:
|
|
* 1. Fetch the Patient from the Bus by local ID to obtain the national identifier.
|
|
* 2. Search DocumentReferences in the Bus by that national identifier.
|
|
* 3. Return the resulting Bundle.
|
|
*
|
|
* Required query parameter:
|
|
* subject — local Patient ID in the Bus.
|
|
*/
|
|
async function findDocumentReferences(req, res, next) {
|
|
try {
|
|
const localPatientIdentifier = req.query.subject;
|
|
if (!localPatientIdentifier) {
|
|
throw createError(400, 'Missing required query parameter: subject');
|
|
}
|
|
const token = await getBusToken(
|
|
config.bus.url,
|
|
config.bus.jwtSecret,
|
|
config.bus.issuer,
|
|
[
|
|
config.bus.mpiScope,
|
|
config.bus.documentRegistryScope
|
|
].join(',')
|
|
);
|
|
// 1. Obtengo el identificador nacional del paciente en forma de referencia
|
|
const patientId = await getPatient(token, localPatientIdentifier);
|
|
if (!patientId) {
|
|
throw createError(422, 'Could not resolve national identifier for the given patient');
|
|
}
|
|
// 2. Obtengo el listado de entradas del indice de atenciones asociadada al id de paciente.
|
|
const bundle = await getDocumentReferencesForPatient(token, patientId);
|
|
|
|
res.status(200).json(bundle);
|
|
} catch (err) {
|
|
next(err);
|
|
}
|
|
}
|
|
|
|
module.exports = { findDocumentReferences };
|