Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- const Stream = require('stream');
- const request = require('request');
- const AWS = require('aws-sdk');
- const s3 = new AWS.S3({apiVersion: '2006-03-01', region: 'ap-northeast-2'});
- // fetch binary from `url` and upload to s3 using `key` as object key
- const store = (url, key) => {
- return new Promise((resolve, reject) => {
- const patchedStream = new Stream.PassThrough();
- request({
- method: 'GET',
- url: url,
- encoding: null // returns body as Buffer
- }).on('error', (e) => {
- // something went wrong during fetch avatar.
- return reject(e);
- }).on('response', (res) => {
- if (res.statusCode.toString().slice(0, 1) !== '2') { // server respond with unexpected status code
- return reject(new Error(`Unexpected status code ${res.statusCode}`));
- }
- s3.upload({
- Bucket: process.env.S3_BUCKET,
- Key: key,
- ContentType: res.headers['content-type'] || 'application/octet-stream',
- Body: patchedStream // note that `res` is Readable Stream, not Buffer.
- }, (e, data) => {
- if (e) { return reject(e); }
- resolve(data);
- });
- }).pipe(patchedStream);
- });
- };
- module.exports = exports = store;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement