Skip to content

Commit

Permalink
improve saveDocument
Browse files Browse the repository at this point in the history
  • Loading branch information
marcusschiesser committed Oct 1, 2024
1 parent 12ed570 commit 3e8057a
Showing 1 changed file with 29 additions and 15 deletions.
44 changes: 29 additions & 15 deletions templates/components/llamaindex/typescript/documents/helper.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import fs from "fs";
import fs from "node:fs";
import path from "node:path";
import { getExtractors } from "../../engine/loader";

const MIME_TYPE_TO_EXT: Record<string, string> = {
Expand All @@ -19,7 +20,8 @@ export async function storeAndParseFile(
if (!fileExt) throw new Error(`Unsupported document type: ${mimeType}`);

const documents = await loadDocuments(fileBuffer, mimeType);
await saveDocument(filename, fileBuffer);
const filepath = path.join(UPLOADED_FOLDER, filename);
await saveDocument(filepath, fileBuffer);
for (const document of documents) {
document.metadata = {
...document.metadata,
Expand All @@ -41,19 +43,31 @@ async function loadDocuments(fileBuffer: Buffer, mimeType: string) {
return await reader.loadDataAsContent(fileBuffer);
}

export async function saveDocument(filename: string, fileBuffer: Buffer) {
const filepath = `${UPLOADED_FOLDER}/${filename}`;
const fileurl = `${process.env.FILESERVER_URL_PREFIX}/${filepath}`;
// Save document to file server and return the file url
export async function saveDocument(filepath: string, content: string | Buffer) {
if (path.isAbsolute(filepath)) {
throw new Error("Absolute file paths are not allowed.");
}
const fileName = path.basename(filepath);
if (!/^[a-zA-Z0-9_.-]+$/.test(fileName)) {
throw new Error(
"File name is not allowed to contain any special characters.",
);
}
if (!process.env.FILESERVER_URL_PREFIX) {
throw new Error("FILESERVER_URL_PREFIX environment variable is not set.");
}

if (!fs.existsSync(UPLOADED_FOLDER)) {
fs.mkdirSync(UPLOADED_FOLDER, { recursive: true });
const dirPath = path.dirname(filepath);
await fs.promises.mkdir(dirPath, { recursive: true });

if (typeof content === "string") {
await fs.promises.writeFile(filepath, content, "utf-8");
} else {
await fs.promises.writeFile(filepath, content);
}
await fs.promises.writeFile(filepath, fileBuffer);

console.log(`Saved document file to ${filepath}.\nURL: ${fileurl}`);
return {
filename,
filepath,
fileurl,
};

const fileurl = `${process.env.FILESERVER_URL_PREFIX}/${filepath}`;
console.log(`Saved document to ${filepath}. Reachable at URL: ${fileurl}`);
return fileurl;
}

0 comments on commit 3e8057a

Please sign in to comment.