2018-02-06 22:31:18 +00:00
|
|
|
const AWS = require('aws-sdk');
|
|
|
|
|
|
|
|
class S3Storage {
|
|
|
|
constructor(config, log) {
|
|
|
|
this.bucket = config.s3_bucket;
|
|
|
|
this.log = log;
|
2019-11-08 16:58:33 +00:00
|
|
|
const cfg = {};
|
|
|
|
if (config.s3_endpoint != '') {
|
|
|
|
cfg['endpoint'] = config.s3_endpoint;
|
|
|
|
}
|
|
|
|
cfg['s3ForcePathStyle'] = config.s3_use_path_style_endpoint
|
|
|
|
AWS.config.update(cfg);
|
|
|
|
this.s3 = new AWS.S3();
|
2018-02-06 22:31:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async length(id) {
|
2019-11-08 16:58:33 +00:00
|
|
|
const result = await this.s3
|
2018-02-06 22:31:18 +00:00
|
|
|
.headObject({ Bucket: this.bucket, Key: id })
|
|
|
|
.promise();
|
|
|
|
return result.ContentLength;
|
|
|
|
}
|
|
|
|
|
|
|
|
getStream(id) {
|
2019-11-08 16:58:33 +00:00
|
|
|
return this.s3.getObject({ Bucket: this.bucket, Key: id }).createReadStream();
|
2018-02-06 22:31:18 +00:00
|
|
|
}
|
|
|
|
|
2018-05-31 21:06:25 +00:00
|
|
|
set(id, file) {
|
2019-11-08 16:58:33 +00:00
|
|
|
const upload = this.s3.upload({
|
2018-02-06 22:31:18 +00:00
|
|
|
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) {
|
2019-11-08 16:58:33 +00:00
|
|
|
return this.s3.deleteObject({ Bucket: this.bucket, Key: id }).promise();
|
2018-02-06 22:31:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
ping() {
|
2019-11-08 16:58:33 +00:00
|
|
|
return this.s3.headBucket({ Bucket: this.bucket }).promise();
|
2018-02-06 22:31:18 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = S3Storage;
|