Function Signature
async function getXMLFromLocalUrl(url: string): Promise<string>
Description
Downloads an XML document from a remote URL and returns it as a UTF-8 encoded string suitable for use with the signXml() function.
Despite the “LocalUrl” naming, this function can fetch from any accessible HTTP/HTTPS URL. It’s useful when XML invoices are stored in cloud storage or generated by remote services.
Parameters
The URL where the XML document is hosted. Must be accessible via HTTP/HTTPS.
Returns
A Promise that resolves to the XML document content as a UTF-8 string, ready to be passed to signXml().
Errors
- Throws network errors if the URL is unreachable
- May throw HTTP errors (404, 403, etc.) if the resource is not available
- May throw timeout errors for slow connections
- May throw parsing errors if the response is not valid text
Example Usage
import { getXMLFromLocalUrl, signXml, getP12FromLocalFile } from './services/signing';
async function signRemoteInvoice() {
// Download XML from URL
const xmlData = await getXMLFromLocalUrl(
'https://example.com/invoices/invoice-001.xml'
);
const p12Data = getP12FromLocalFile('./certificate.p12');
// Sign the document
const signedXml = await signXml(
p12Data,
'certificate-password',
xmlData
);
return signedXml;
}
Example with API Integration
import { getXMLFromLocalUrl, signXml, getP12FromUrl } from './services/signing';
async function processInvoiceFromAPI(invoiceId: string) {
// Fetch XML from your API
const xmlUrl = `https://api.example.com/invoices/${invoiceId}/xml`;
const certUrl = 'https://secure.example.com/certificates/active.p12';
try {
// Load both XML and certificate from URLs
const [xmlData, p12Data] = await Promise.all([
getXMLFromLocalUrl(xmlUrl),
getP12FromUrl(certUrl)
]);
// Sign the document
const signedXml = await signXml(p12Data, process.env.CERT_PASSWORD!, xmlData);
console.log(`Invoice ${invoiceId} signed successfully`);
return signedXml;
} catch (error) {
console.error(`Failed to process invoice ${invoiceId}:`, error);
throw error;
}
}
Example with Retry Logic
import { getXMLFromLocalUrl } from './services/signing';
async function fetchXMLWithRetry(
url: string,
maxRetries: number = 3
): Promise<string> {
for (let i = 0; i < maxRetries; i++) {
try {
const xml = await getXMLFromLocalUrl(url);
return xml;
} catch (error) {
console.warn(`Attempt ${i + 1} failed, retrying...`);
if (i === maxRetries - 1) throw error;
// Wait before retrying (exponential backoff)
await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, i)));
}
}
throw new Error('Max retries exceeded');
}
Source: src/services/signing.ts:26