Created
October 14, 2019 10:33
-
-
Save shrimp2t/f592897be893715e1a7a97d39b0b200d 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
require('dotenv').config(); | |
const stream = require('stream'); | |
const axios = require('axios'); | |
const AWS = require('aws-sdk'); | |
const mime = require('mime-types'); | |
const path = require('path'); | |
class S3RemoteUploader { | |
constructor(remoteAddr, fileName) { | |
this.remoteAddr = remoteAddr; | |
this.stream = stream; | |
this.axios = axios; | |
this.config = { | |
endpoint: process.env.AWS_DESIGN_END_POINT, | |
api_key: process.env.AWS_KEY, | |
api_secret: process.env.AWS_SECRET_KEY, | |
subfolder: process.env.AWS_SUBFOLDER, | |
acl: process.env.AWS_ALC, | |
bucket: process.env.AWS_DESIGN_BUCKET | |
}; | |
this.AWS = AWS; | |
this.AWS.config.update({ | |
accessKeyId: this.config.api_key, | |
secretAccessKey: this.config.api_secret | |
}); | |
this.spacesEndpoint = new this.AWS.Endpoint(this.config.endpoint); | |
this.s3 = new this.AWS.S3({ endpoint: this.spacesEndpoint }); | |
let fileInfo = path.parse(remoteAddr); | |
if (fileName) { | |
this.file_name = fileName + '.png'; | |
} else { | |
this.file_name = this.remoteAddr.substring(this.remoteAddr.lastIndexOf('/') + 1); | |
} | |
this.obj_key = this.config.subfolder + '/' + this.file_name; | |
if (fileInfo.ext) { | |
this.content_type = mime.lookup(fileInfo.ext); | |
} else { | |
this.content_type = 'application/octet-stream'; | |
} | |
this.uploadStream(); | |
} | |
uploadStream() { | |
const pass = new this.stream.PassThrough(); | |
this.promise = this.s3 | |
.upload({ | |
Bucket: this.config.bucket, | |
Key: this.obj_key, | |
ACL: this.config.acl, | |
Body: pass, | |
ContentType: this.content_type | |
}) | |
.promise(); | |
return pass; | |
} | |
initiateAxiosCall() { | |
return axios({ | |
method: 'get', | |
url: this.remoteAddr, | |
responseType: 'stream' | |
}); | |
} | |
async dispatch() { | |
await this.initiateAxiosCall().then((response) => { | |
if (response.status === 200) { | |
this.content_type = response.headers['content-type']; | |
response.data.pipe(this.uploadStream()); | |
} | |
}); | |
return this.promise; | |
} | |
} | |
module.exports = S3RemoteUploader; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment