import { Readable } from "stream"; import BaseStorage from "../BaseStorage.js"; import { S3Client, GetObjectCommand, PutObjectCommand, DeleteObjectCommand, ListObjectsV2Command } from "@aws-sdk/client-s3"; import { LocalFile } from "@entity-access/server-pages/dist/core/LocalFile.js"; import { globalEnv } from "../../../common/globalEnv.js"; const Bucket = globalEnv.s3.bucket ?? "test-bucket"; export default class S3Storage extends BaseStorage { private client: S3Client; constructor() { super(); const { endpoint, accessKeyId, secretAccessKey, region } = globalEnv.s3; this.client = new S3Client({ endpoint, credentials: { accessKeyId, secretAccessKey }, forcePathStyle: endpoint ? true : false, region, }); } async verify() { await this.client.send(new ListObjectsV2Command({ Bucket, MaxKeys: 1 })); } async streamFile(Key: string): Promise<{ contentType: string, stream: Readable }> { const r = await this.client.send(new GetObjectCommand({ Bucket, Key })); return { contentType: r.ContentType, stream: r.Body as Readable } ; } async createFile(Key: string, file: LocalFile): Promise { const [ChecksumSHA256, ContentMD5] = await Promise.all([ this.cryptoService.hashBuffer(file.openRead(), "base64"), this.cryptoService.md5Buffer(file.openRead()) ]); const Body = file.openReadStream(); await this.client.send(new PutObjectCommand({ Bucket, Key, ChecksumSHA256, ContentMD5, Body })); return Key; } async deleteFile(Key: string) { await this.client.send(new DeleteObjectCommand({ Bucket, Key })); } }