Created
November 23, 2017 17:21
-
-
Save vampaynani/864dc9f010e9b7fef1122afe1ab80f4e to your computer and use it in GitHub Desktop.
AWS S3 mock
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
import aws from 'aws-sdk'; | |
// ======================================== | |
// ! Sign | |
/* | |
* AWS connection to get the signed url | |
*/ | |
// ======================================== | |
const sign = (req, res) => { | |
const { AWS_KEY_ID, AWS_SECRET_ID, AWS_REGION, AWS_BUCKET, AWS_EXPIRY_TIME } = process.env; | |
aws.config.update({ | |
accessKeyId: AWS_KEY_ID, | |
secretAccessKey: AWS_SECRET_ID, | |
region: AWS_REGION | |
}); | |
const bucket = AWS_BUCKET; | |
const s3 = new aws.S3(); | |
s3.getSignedUrl('getObject', { | |
Key: req.params.filename, | |
Bucket: AWS_BUCKET, | |
Expires: EXPIRY_TIME | |
}, | |
function(err, response) { | |
if (!err && response) { | |
res.status(200).json(response); | |
} else { | |
res.status(500).json(err); | |
} | |
}); | |
} | |
// ======================================== | |
// ! Upload | |
/* | |
* Upload documents to the aws bucket | |
*/ | |
// ======================================== | |
const upload = (req, res) => { | |
const { AWS_KEY_ID, AWS_SECRET_ID, AWS_REGION, AWS_BUCKET, AWS_EXPIRY_TIME } = process.env; | |
aws.config.update({ | |
accessKeyId: AWS_KEY_ID, | |
secretAccessKey: AWS_SECRET_ID, | |
region: AWS_REGION | |
}); | |
const s3 = new aws.S3({ | |
params:{ | |
Bucket: AWS_BUCKET | |
} | |
}); | |
if ( !req.file.name ) { | |
return res.json({ code: 500, error: 'No file' }); | |
} | |
s3.putObject({ | |
Key: req.file.name, | |
Body: fs.createReadStream(req.file.path), | |
ContentType: req.file.mimetype | |
}, | |
function(err, response) { | |
if (!err && response) { | |
res.status(200).json(response); | |
} else { | |
res.status(500).json(err); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment