nathan-pichon 61d1039e67 fix(aws-provider): add https protocol when missing in file url
Adding hard coded https:// to url because Digital Ocean only gives the uri without protocol in response to the upload.

Fix #14288
2022-10-19 09:43:05 +02:00

83 lines
2.0 KiB
JavaScript

'use strict';
/**
* Module dependencies
*/
/* eslint-disable no-unused-vars */
// Public node modules.
const _ = require('lodash');
const AWS = require('aws-sdk');
function assertUrlProtocol(url) {
// Regex to test protocol like "http://", "https://"
return /^\w*:\/\//.test(url);
}
module.exports = {
init(config) {
const S3 = new AWS.S3({
apiVersion: '2006-03-01',
...config,
});
const upload = (file, customParams = {}) =>
new Promise((resolve, reject) => {
// upload file on S3 bucket
const path = file.path ? `${file.path}/` : '';
S3.upload(
{
Key: `${path}${file.hash}${file.ext}`,
Body: file.stream || Buffer.from(file.buffer, 'binary'),
ACL: 'public-read',
ContentType: file.mime,
...customParams,
},
(err, data) => {
if (err) {
return reject(err);
}
// set the bucket file url
if (assertUrlProtocol(data.Location)) {
file.url = data.Location;
} else {
// Default protocol to https protocol
file.url = `https://${data.Location}`;
}
resolve();
}
);
});
return {
uploadStream(file, customParams = {}) {
return upload(file, customParams);
},
upload(file, customParams = {}) {
return upload(file, customParams);
},
delete(file, customParams = {}) {
return new Promise((resolve, reject) => {
// delete file on S3 bucket
const path = file.path ? `${file.path}/` : '';
S3.deleteObject(
{
Key: `${path}${file.hash}${file.ext}`,
...customParams,
},
(err, data) => {
if (err) {
return reject(err);
}
resolve();
}
);
});
},
};
},
};