@ejekanshjain/cloud-storage
Version:
All in one package to handle files accross cloud storage services
56 lines • 1.86 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.S3Client = void 0;
const client_s3_1 = require("@aws-sdk/client-s3");
const zod_1 = require("zod");
const S3ClientOptionsZ = zod_1.z.object({
region: zod_1.z.string().min(1),
accessKey: zod_1.z.string().min(1),
accessSecret: zod_1.z.string().min(1),
bucket: zod_1.z.string().min(1),
host: zod_1.z.string().optional()
});
const S3Client = (options) => {
const { region, accessKey, accessSecret, bucket, host } = S3ClientOptionsZ.parse(options);
const s3Client = new client_s3_1.S3Client({
region: region,
credentials: {
accessKeyId: accessKey,
secretAccessKey: accessSecret
},
endpoint: host,
forcePathStyle: !!host
});
const addFile = async (options) => {
await s3Client.send(new client_s3_1.PutObjectCommand({
Bucket: bucket,
Key: options.filename,
Body: options.data
}));
return host
? `${host}/${bucket}/${options.filename}`
: `https://${bucket}.s3.${region}.amazonaws.com/${options.filename}`;
};
const deleteFile = async (filename) => {
await s3Client.send(new client_s3_1.DeleteObjectCommand({
Bucket: bucket,
Key: filename
}));
};
const getFile = async (filename) => {
const response = await s3Client.send(new client_s3_1.GetObjectCommand({
Bucket: bucket,
Key: filename
}));
if (!response.Body)
throw new Error('AWS S3: No body in response');
return Buffer.from((await response.Body.transformToByteArray()).buffer);
};
return {
addFile,
deleteFile,
getFile
};
};
exports.S3Client = S3Client;
//# sourceMappingURL=s3.js.map