import { Document } from "../types"; import { PDFDocumentLoader } from "./pdf"; import { DocxDocumentLoader } from "./docx"; import { TextDocumentLoader } from "./text"; import * as path from "path"; export class DocumentLoaderFactory { private pdfLoader = new PDFDocumentLoader(); private docxLoader = new DocxDocumentLoader(); private textLoader = new TextDocumentLoader(); private supportedExtensions = new Map([ ["pdf", "pdf"], ["docx", "docx"], ["doc", "docx"], // Treat .doc files as docx ["txt", "text"], ["text", "text"], ["md", "text"], ["markdown", "text"], ]); async loadDocument(filePath: string, content: Buffer): Promise { const extension = this.getFileExtension(filePath); const loaderType = this.supportedExtensions.get(extension); if (!loaderType) { throw new Error(`Unsupported file type: ${extension}`); } console.log(`[DocumentLoaderFactory] Loading ${filePath} as ${loaderType}`); switch (loaderType) { case "pdf": return await this.pdfLoader.load(filePath, content); case "docx": return await this.docxLoader.load(filePath, content); case "text": return await this.textLoader.load(filePath, content); default: throw new Error(`Unsupported loader type: ${loaderType}`); } } private getFileExtension(filePath: string): string { return path.extname(filePath).toLowerCase().slice(1); } getSupportedExtensions(): string[] { return Array.from(this.supportedExtensions.keys()); } isSupported(filePath: string): boolean { const extension = this.getFileExtension(filePath); return this.supportedExtensions.has(extension); } }