common-core-pkg
Version:
Common package for all the utils
63 lines • 2.19 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.S3Service = void 0;
const client_s3_1 = require("@aws-sdk/client-s3");
const s3_request_presigner_1 = require("@aws-sdk/s3-request-presigner");
class S3Service {
constructor(bucket, region) {
this.bucket = bucket;
this.region = region;
const accessKeyId = process.env.ACCESS_KEY_ID;
const secretAccessKey = process.env.SECRET_ACCESS_KEY;
if (accessKeyId === undefined || secretAccessKey === undefined) {
throw new Error("AWS credentials are not set in environment variables.");
}
this.s3 = new client_s3_1.S3Client({
region: this.region,
credentials: {
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
},
});
}
async uploadObject(key, file, options = {}) {
await this.s3.send(new client_s3_1.PutObjectCommand({
Bucket: this.bucket,
Key: key,
Body: file,
...options,
}));
return `https://${this.bucket}.s3.${this.region}.amazonaws.com/${key}`;
}
async deleteObject(key) {
await this.s3.send(new client_s3_1.DeleteObjectCommand({
Bucket: this.bucket,
Key: key,
}));
return true;
}
async getObject(key) {
const response = await this.s3.send(new client_s3_1.GetObjectCommand({
Bucket: this.bucket,
Key: key,
}));
if (!response.Body) {
throw new Error("File not found or empty response.");
}
const stream = response.Body;
const chunks = [];
for await (const chunk of stream) {
chunks.push(chunk);
}
return Buffer.concat(chunks);
}
async getSignedUrl(key, expiresIn = 3600) {
const command = new client_s3_1.GetObjectCommand({
Bucket: this.bucket,
Key: key,
});
return await (0, s3_request_presigner_1.getSignedUrl)(this.s3, command, { expiresIn });
}
}
exports.S3Service = S3Service;
//# sourceMappingURL=s3.service.js.map