2018-02-06 22:31:18 +00:00
|
|
|
const AWS = require('aws-sdk');
|
2019-11-08 16:44:04 +00:00
|
|
|
const config = {};
|
|
|
|
if (typeof process.env.AWS_S3_ENDPOINT !== 'undefined') {
|
|
|
|
config['endpoint'] = process.env.AWS_S3_ENDPOINT;
|
|
|
|
}
|
|
|
|
if (typeof process.env.AWS_S3_USE_PATH_STYLE_ENDPOINT !== 'undefined') {
|
|
|
|
config['s3ForcePathStyle'] = process.env.AWS_S3_USE_PATH_STYLE_ENDPOINT == 'true' ? true : false;
|
|
|
|
}
|
|
|
|
AWS.config.update(config);
|
2018-02-06 22:31:18 +00:00
|
|
|
const s3 = new AWS.S3();
|
|
|
|
|
|
|
|
class S3Storage {
|
|
|
|
constructor(config, log) {
|
|
|
|
this.bucket = config.s3_bucket;
|
|
|
|
this.log = log;
|
|
|
|
}
|
|
|
|
|
|
|
|
async length(id) {
|
|
|
|
const result = await s3
|
|
|
|
.headObject({ Bucket: this.bucket, Key: id })
|
|
|
|
.promise();
|
|
|
|
return result.ContentLength;
|
|
|
|
}
|
|
|
|
|
|
|
|
getStream(id) {
|
|
|
|
return s3.getObject({ Bucket: this.bucket, Key: id }).createReadStream();
|
|
|
|
}
|
|
|
|
|
2018-05-31 21:06:25 +00:00
|
|
|
set(id, file) {
|
2018-02-06 22:31:18 +00:00
|
|
|
const upload = s3.upload({
|
|
|
|
Bucket: this.bucket,
|
|
|
|
Key: id,
|
|
|
|
Body: file
|
|
|
|
});
|
2018-05-31 21:06:25 +00:00
|
|
|
file.on('error', () => upload.abort());
|
|
|
|
return upload.promise();
|
2018-02-06 22:31:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
del(id) {
|
|
|
|
return s3.deleteObject({ Bucket: this.bucket, Key: id }).promise();
|
|
|
|
}
|
|
|
|
|
|
|
|
ping() {
|
|
|
|
return s3.headBucket({ Bucket: this.bucket }).promise();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = S3Storage;
|