hostr/lib/s3.js

37 lines
972 B
JavaScript
Raw Permalink Normal View History

2015-07-09 23:01:43 +01:00
import aws from 'aws-sdk';
import debugname from 'debug';
2018-06-02 18:07:00 +00:00
2015-07-09 23:01:43 +01:00
const debug = debugname('hostr:s3');
2018-06-02 15:50:39 +00:00
const s3 = new aws.S3({
endpoint: process.env.AWS_ENDPOINT,
s3ForcePathStyle: true,
signatureVersion: 'v4',
});
2015-07-09 23:01:43 +01:00
export function get(key) {
2018-06-02 15:50:39 +00:00
let fullKey = `uploads/${key}`;
2016-06-06 13:39:42 +01:00
if (key.substr(2, 5) === '970/' || key.substr(2, 5) === '150/') {
2018-06-02 15:50:39 +00:00
fullKey = `uploads/${key.substr(2)}`;
2016-06-06 13:39:42 +01:00
}
debug('fetching from s3: %s', fullKey);
2018-06-02 15:50:39 +00:00
return s3.getObject({ Bucket: process.env.AWS_BUCKET, Key: fullKey })
.createReadStream()
.on('error', (err) => {
debug('S3 error', err);
});
}
export function upload(stream, key) {
2018-06-02 15:50:39 +00:00
debug(`sending to s3: uploads/'${key}`);
const params = { Bucket: process.env.AWS_BUCKET, Key: `uploads/${key}`, Body: stream };
const uploading = s3.upload(params);
uploading.on('error', (err) => {
debug('S3 Error', err);
});
uploading.send((err) => {
debug('S3 Connection Error', err);
});
2018-06-02 15:50:39 +00:00
return uploading;
2015-07-09 23:01:43 +01:00
}