@cpmech/az-s3
Version:
AmaZon S3 Tools
93 lines (84 loc) • 2.62 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var awsSdk = require('aws-sdk');
var util = require('@cpmech/util');
// returns the filekeys of those deleted successfully
const deleteObjects = async (bucket, filekeys, quiet = true, s3Config) => {
const s3 = new awsSdk.S3(s3Config);
const res = await s3
.deleteObjects({
Bucket: bucket,
Delete: {
Objects: filekeys.map(k => ({ Key: k })),
Quiet: quiet,
},
})
.promise();
const { Deleted } = res;
if (!Deleted) {
throw new Error('cannot delete objects');
}
return Deleted.reduce((acc, curr) => {
if (curr.Key) {
acc.push(curr.Key);
}
return acc;
}, []);
};
// NOTE: the path must have a FileExt
const getDownloadUrl = (bucket, path, expireSeconds, s3Config) => {
const s3 = new awsSdk.S3(s3Config);
return s3.getSignedUrl('getObject', {
Bucket: bucket,
Key: path,
Expires: expireSeconds,
});
};
const getStringObject = async (bucket, filekey, s3Config) => {
const s3 = new awsSdk.S3(s3Config);
const res = await s3
.getObject({
Bucket: bucket,
Key: filekey,
})
.promise();
if (!res || !res.Body) {
throw new Error(`cannot get string object with filekey = ${filekey}`);
}
return String(res.Body);
};
// get upload URL
const getUploadUrl = (bucket, filekey, expiresSeconds = 60, s3Config) => {
const ext = util.name2fileExt(filekey);
if (!ext) {
throw new Error('file extension must be given in filekey');
}
const s3 = new awsSdk.S3(s3Config);
const url = s3.getSignedUrl('putObject', {
Bucket: bucket,
Key: filekey,
ContentType: util.fileExt2contentType[ext],
Expires: expiresSeconds,
});
return url;
};
// put data on S3 and returns the filekey
// NOTE: the given filekey should have a FileExt
const putStringObject = async (data, bucket, filekey, s3Config) => {
const ext = util.name2fileExt(filekey);
const s3 = new awsSdk.S3(s3Config);
await s3
.putObject({
Bucket: bucket,
Key: filekey,
Body: data,
ContentType: util.fileExt2contentType[ext],
})
.promise();
return filekey;
};
exports.deleteObjects = deleteObjects;
exports.getDownloadUrl = getDownloadUrl;
exports.getStringObject = getStringObject;
exports.getUploadUrl = getUploadUrl;
exports.putStringObject = putStringObject;