const createError = require('http-errors'); const axios = require('axios'); async function getRemoteDocument(url){ const response = await axios.get(parsedUrl.toString(), { responseType: 'arraybuffer', headers: { Accept: req.headers['accept'] || '*/*', }, }); return response } /** * ITI-68: Retrieve Document (MHD) * * GET /fhir/Binary?url=[URL_Directa] * * Flow (diagram iti67.mmd, step 21-24): * 1. HIS_A supplies the direct document URL obtained from a prior ITI-67 response. * 2. This gateway performs a P2P GET to that URL, bypassing the Bus. * 3. The raw document (PDF, XML, etc.) is forwarded back to HIS_A. */ async function download(req, res, next) { try { const url = req.query.url; if (!url) { throw createError(400, 'Missing required query parameter: url'); } let parsedUrl; try { parsedUrl = new URL(url); } catch { throw createError(400, 'Invalid document URL'); } const response = await getRemoteDocument(url); const contentType = response.headers['content-type']; if (contentType) res.setHeader('Content-Type', contentType); const contentDisposition = response.headers['content-disposition']; if (contentDisposition) res.setHeader('Content-Disposition', contentDisposition); res.status(200).send(response.data); } catch (err) { if (err.response) { return next(createError(err.response.status, `Document source returned ${err.response.status}`)); } next(err); } } module.exports = { download };