@opengis/fastify-table
Version:
core-plugins
47 lines (46 loc) • 1.61 kB
JavaScript
import { GetObjectCommand } from "@aws-sdk/client-s3";
import { readFile } from "node:fs/promises";
import { createReadStream } from "node:fs";
import s3Client from "../client.js";
import config from "../../../../../../config.js";
import streamToBuffer from "../../utils/streamToBuffer.js";
// if not found on s3 => fs
import fsFuncs from "../../fs.js";
import getPath from "../../../utils/getPath.js";
import getS3FilePath from "./utils/getS3FilePath.js";
const getFileStream = (s3Settings) => async (fp, options = {}) => {
const filepath = getS3FilePath(fp, s3Settings);
const bucketParams = {
Bucket: s3Settings?.containerName || config.s3?.containerName || "work",
Key: filepath[0] === "/" ? filepath?.slice(1) : filepath,
Range: options.Range,
};
try {
const data = await s3Client.send(new GetObjectCommand(bucketParams));
if (options.buffer) {
return streamToBuffer(data.Body);
}
return data.Body;
}
catch (err) {
// disable fs fallback for chunked download from s3
if (options.fallback === false) {
return null;
}
const filepath1 = getPath(fp, options);
if (!filepath1) {
return null;
}
const { fileExists } = fsFuncs();
const exists = await fileExists(filepath1);
if (!exists) {
return null;
}
if (options.buffer) {
return readFile(filepath1);
}
const fileStream = createReadStream(filepath1);
return fileStream;
}
};
export default getFileStream;