Avanzado

Descargadores personalizados

Cómo implementar DownloaderInterface para agregar caché local, proxies, reintentos o stubs de pruebas.

Todos los retrievers delegan la transferencia de archivos a un objeto que implemente DownloaderInterface:

export interface DownloaderInterface {
  downloadTo: (source: string, destination: string) => Promise<void>;
}

Antes de invocar downloadTo(source, destination), AbstractBaseRetriever.download() ya creó el directorio padre de destination de forma recursiva.

AbstractXmlRetriever ejecuta descargas de dependencias hermanas en paralelo (hasta maxConcurrentDownloads(), por defecto 6). Tu implementación de DownloaderInterface debe ser segura ante llamadas concurrentes sin compartir estado mutable por petición.

Descargador con caché local

Puedes envolver NodeDownloader para omitir la descarga cuando el archivo ya existe en disco:

src/cached_downloader.ts
import type { DownloaderInterface } from '@nodecfdi/xml-resource-retriever/types';
import { access } from 'node:fs/promises';
import { NodeDownloader, XsdRetriever } from '@nodecfdi/xml-resource-retriever';

export class CachedDownloader implements DownloaderInterface {
  public constructor(private readonly inner: DownloaderInterface = new NodeDownloader()) {}

  public async downloadTo(source: string, destination: string): Promise<void> {
    try {
      await access(destination);
    } catch {
      await this.inner.downloadTo(source, destination);
    }
  }
}

const retriever = new XsdRetriever('./storage/xsd', new CachedDownloader());
await retriever.retrieve('http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd');

Descargador de respaldo o para pruebas

También puedes crear un descargador que devuelva contenido local o simulado para pruebas unitarias o para tolerar recursos temporalmente inaccesibles:

tests/stub_downloader.ts
import type { DownloaderInterface } from '@nodecfdi/xml-resource-retriever/types';
import { writeFile } from 'node:fs/promises';
import { XsltRetriever } from '@nodecfdi/xml-resource-retriever';

const fixtures: Record<string, string> = {
  'http://example.test/main.xslt':
    '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"/>',
};

const stubDownloader: DownloaderInterface = {
  async downloadTo(source, destination) {
    const content = fixtures[source];
    if (content === undefined) {
      throw new Error(`Fixture no encontrado para ${source}`);
    }

    await writeFile(destination, content, 'utf8');
  },
};

const retriever = new XsltRetriever('./tmp/test-storage', stubDownloader);
await retriever.retrieve('http://example.test/main.xslt');