@opengis/fastify-table
Version:
core-plugins
51 lines (43 loc) • 1.43 kB
JavaScript
import {
GetObjectCommand,
} from '@aws-sdk/client-s3';
import { readFile } from 'node:fs/promises';
import { createReadStream } from 'node:fs';
import client from '../client.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 s3Client = client.getS3Client(s3Settings);
const bucketName = s3Settings.containerName;
const bucketParams = {
Bucket: bucketName,
Key: filepath[0] === '/' ? filepath?.slice(1) : filepath,
};
try {
const data = await s3Client.send(new GetObjectCommand(bucketParams));
if (options.buffer) {
return streamToBuffer(data.Body);
}
return data.Body;
}
catch (err) {
const filepath1 = getPath(fp, options);
const { fileExists } = fsFuncs();
const exists = await fileExists(filepath1);
if (!exists) {
return null;
}
if (options.buffer) {
return readFile(filepath1);
}
const fileStream = createReadStream(filepath1);
return fileStream;
// return null;
// // throw new Error('Файл не знайдено');
}
};
export default getFileStream;