Skip to content

Instantly share code, notes, and snippets.

@fdorantesm
Created March 13, 2020 17:44
Show Gist options
  • Save fdorantesm/30bc11e04b1096a558cd82436c8ee343 to your computer and use it in GitHub Desktop.
Save fdorantesm/30bc11e04b1096a558cd82436c8ee343 to your computer and use it in GitHub Desktop.
AWS Helpers
const AWS = require('aws-sdk')
const uuidBase62 = require('uuid-base62')
const mailcomposer = require('mailcomposer')
/**
* Upload file to AWS S3 Service
* @param {Buffer} f
* @param {String} path
* @param {String} filename Uploaded file's name
* @return {Promise<Object>} S3 Promise
*/
exports.upload = (f, path, filename) => {
AWS.config.update({
accessKeyId: process.env.AMAZON_ACCESS_KEY_ID,
secretAccessKey: process.env.AMAZON_SECRET_ACCESS_KEY,
region: process.env.AWS_S3_BUCKET_REGION
})
let s3 = new AWS.S3()
filename = filename || uuidBase62.v4()
let params = {
Bucket: process.env.AWS_S3_BUCKET_NAME,
Body: f,
Key: `${path}/${filename}`,
ACL: 'public-read'
}
return s3.upload(params).promise()
}
/**
* Send email using AWS Simple Email Service
* @param {Array|String} to Email or email list
* @param {String} subject
* @param {String} text
* @param {Array} attachments
* @return {Promise<Object>} SES Promise
*/
exports.email = async (to, subject, text, attachments = []) => {
AWS.config.update({ region: process.env.AWS_SES_REGION })
const mail = mailcomposer({
from: process.env.SENDER_EMAIL,
replyTo: process.env.SENDER_EMAIL,
to: isArray(to) ? to : [to],
subject: subject,
text: text,
attachments: attachments.map(attachment => ({ path: attachment }))
})
return new Promise((resolve, reject) => {
mail.build((err, message) => {
if (err) {
return reject(err)
}
const emailPromise = new AWS.SES({
apiVersion: '2010-12-01',
credentials: {
accessKeyId: process.env.AWS_SES_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SES_SECRET_ACCESS_KEY
}
}).sendRawEmail({ RawMessage: { Data: message } }).promise()
resolve(emailPromise)
})
})
}
/**
* Invokes lambda function
* @void
* @param {Object} params Lambda arguments
*/
exports.invokeLamda = params => {
AWS.config.update({
accessKeyId: process.env.AMAZON_ACCESS_KEY_ID,
secretAccessKey: process.env.AMAZON_SECRET_ACCESS_KEY,
region: process.env.AWS_S3_BUCKET_REGION
})
const lambda = new AWS.Lambda()
return lambda.invoke(params).promise()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment