Created
September 5, 2018 12:29
-
-
Save kilgarenone/8e2c7c6b5cf55707bb46469dc41111ce to your computer and use it in GitHub Desktop.
axios serverless with third-party API
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
const axios = require("axios"); | |
const mailChimp = { | |
preLaunchListId: "ff8c031f0e", // you can find yours in your mailchimp dashboard | |
apiUrl: "https://us2.api.mailchimp.com/3.0/" // this too | |
}; | |
module.exports.addToBetaUserList = function(event, context, callback) { | |
const body = JSON.parse(event.body); // accessing the POST body payload. yours might have different structure and names | |
const auth = { | |
username: "johnDough", | |
password: process.env.MAILCHIMP_API_KEY // we set this earlier in the serverless.yml file | |
}; | |
const user = { | |
email_address: body.emailAddress, // we set 'emailAddress' key in the front-end | |
status: "subscribed" // signifies user is subscribed for mailchimp(https://goo.gl/ejX1nu) | |
}; | |
axios | |
.post( | |
`${mailChimp.apiUrl}lists/${mailChimp.preLaunchListId}/members/`, | |
user, | |
{ auth, headers: { "content-type": "application/json" } } | |
) | |
.then(function() { | |
const response = { | |
statusCode: 200, | |
headers: { | |
"Access-Control-Allow-Origin": "*", // Required for CORS support to work | |
"Access-Control-Allow-Credentials": true // Required for cookies, authorization headers with HTTPS | |
}, | |
body: JSON.stringify({ | |
message: "Successfully added to beta user list!" | |
}) | |
}; | |
callback(null, response); | |
}) | |
.catch(e => { | |
const error = e.response.data; | |
const errorResponse = { | |
statusCode: error.status, | |
headers: { | |
"Access-Control-Allow-Origin": "*", // Required for CORS support to work | |
"Access-Control-Allow-Credentials": true // Required for cookies, authorization headers with HTTPS | |
}, | |
body: JSON.stringify({ | |
message: error.title | |
}) | |
}; | |
callback(null, errorResponse); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment