Advertisement
Guest User

Untitled

a guest
Feb 19th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. 'use strict';
  2.  
  3. const Stream = require('stream');
  4. const request = require('request');
  5. const AWS = require('aws-sdk');
  6.  
  7. const s3 = new AWS.S3({apiVersion: '2006-03-01', region: 'ap-northeast-2'});
  8.  
  9. // fetch binary from `url` and upload to s3 using `key` as object key
  10. const store = (url, key) => {
  11. return new Promise((resolve, reject) => {
  12. const patchedStream = new Stream.PassThrough();
  13.  
  14. request({
  15. method: 'GET',
  16. url: url,
  17. encoding: null // returns body as Buffer
  18. }).on('error', (e) => {
  19. // something went wrong during fetch avatar.
  20. return reject(e);
  21. }).on('response', (res) => {
  22. if (res.statusCode.toString().slice(0, 1) !== '2') { // server respond with unexpected status code
  23. return reject(new Error(`Unexpected status code ${res.statusCode}`));
  24. }
  25.  
  26. s3.upload({
  27. Bucket: process.env.S3_BUCKET,
  28. Key: key,
  29. ContentType: res.headers['content-type'] || 'application/octet-stream',
  30. Body: patchedStream // note that `res` is Readable Stream, not Buffer.
  31. }, (e, data) => {
  32. if (e) { return reject(e); }
  33.  
  34. resolve(data);
  35. });
  36. }).pipe(patchedStream);
  37. });
  38. };
  39.  
  40.  
  41. module.exports = exports = store;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement