Files
FEDEO/backend/src/utils/fileBuffer.ts

31 lines
986 B
TypeScript

import { GetObjectCommand } from "@aws-sdk/client-s3"
import { s3 } from "./s3"
import { secrets } from "./secrets"
export const streamToBuffer = async (stream: any, maxBytes = Infinity): Promise<Buffer> => {
const chunks: Buffer[] = []
let size = 0
for await (const chunk of stream) {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
size += buffer.length
if (size > maxBytes) throw new Error("Die Datei ist für Base64 zu groß. Bitte den Download mit format: url verwenden.")
chunks.push(buffer)
}
return Buffer.concat(chunks)
}
export const loadFileBuffer = async (path: string, maxBytes = Infinity): Promise<Buffer> => {
const response = await s3.send(new GetObjectCommand({
Bucket: secrets.S3_BUCKET,
Key: path,
}))
if (!response.Body) {
throw new Error(`S3-Datei '${path}' enthält keinen lesbaren Inhalt.`)
}
return streamToBuffer(response.Body, maxBytes)
}