Created
April 2, 2019 00:57
-
-
Save SachaG/c075cfefe0298c132ae7cf973ab01888 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
AWS Utilities | |
*/ | |
import AWS from 'aws-sdk'; | |
import request from 'request'; | |
import rp from 'request-promise'; | |
import { getSetting } from 'meteor/vulcan:core'; | |
import aws4 from 'aws4'; | |
import { parse } from 'url'; | |
/* | |
S3 constants | |
*/ | |
const region = getSetting('digitalocean.region'); | |
const accessKey = getSetting('digitalocean.accessKey'); | |
const secret = getSetting('digitalocean.accessKeySecret'); | |
const bucket = getSetting('digitalocean.bucket'); | |
const host = `${region}.digitaloceanspaces.com`; | |
/* | |
S3 config | |
*/ | |
const spacesEndpoint = new AWS.Endpoint(host); | |
const s3 = new AWS.S3({ | |
endpoint: spacesEndpoint, | |
accessKeyId: accessKey, | |
secretAccessKey: secret, | |
}); | |
/* | |
AWS constant options for AWS4 signature | |
*/ | |
const aws4opts = { | |
service: 's3', | |
region, | |
host, | |
}; | |
/* | |
Take a file URL, and upload the file to S3 | |
*/ | |
export const putFromUrl = async (url, key) => { | |
try { | |
const response = await rp({ | |
url: url, | |
encoding: null, | |
resolveWithFullResponse: true, | |
// when loading contract PDFs or other private content, we need to authentify using Vulcan's own apiKey | |
headers: { | |
apikey: getSetting('vulcan.apiKey'), | |
}, | |
}); | |
const s3params = { | |
Bucket: bucket, | |
Key: key, | |
ContentType: response.headers['content-type'], | |
ContentLength: response.headers['content-length'], | |
Body: response.body, // buffer | |
}; | |
await s3.putObject(s3params).promise(); | |
} catch (error) { | |
console.log('// putFromUrl error'); // eslint-disable-line | |
console.log(error); // eslint-disable-line | |
} | |
}; | |
/* | |
Take an S3 file URL, authenticate, and return a stream | |
*/ | |
export const getS3File = (url) => { | |
const path = parse(url).pathname.slice(1); // remove leading "/" | |
const opts = { | |
...aws4opts, | |
path, | |
url, | |
}; | |
aws4.sign(opts, { accessKeyId: accessKey, secretAccessKey: secret }); | |
const stream = request(opts); | |
return stream; | |
}; | |
/* | |
Take an S3 file URL, authenticate, and return a response (async version) | |
*/ | |
export const getS3FileAsync = async (url) => { | |
const path = parse(url).pathname.slice(1); // remove leading "/" | |
const opts = { | |
...aws4opts, | |
path, | |
url, | |
}; | |
aws4.sign(opts, { accessKeyId: accessKey, secretAccessKey: secret }); | |
const response = await rp(opts); | |
return response; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment