Last active
October 8, 2018 19:55
-
-
Save tylrd/6667a09d41c7ff84091619a1f3032369 to your computer and use it in GitHub Desktop.
Pass-through API for NodeJS lambda
This file contains 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 https = require('https'); | |
const handler = async (event, context, callback) => { | |
const options = { | |
host: 'jsonplaceholder.typicode.com', | |
path: '/todos/1', | |
}; | |
const postOptions = { | |
host: 'jsonplaceholder.typicode.com', | |
path: '/todos', | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json' | |
} | |
}; | |
// Use promise chaining to put the result of the first promise into the second | |
// The resolve in the first promise will be the "todo" variable in the .then | |
return new Promise((resolve, reject) => { | |
https.get(options, res => { | |
var body = ''; | |
res.on('data', data => { | |
body += data; | |
}) | |
res.on('end', () => { | |
const jsonData = JSON.parse(body) | |
resolve(jsonData) | |
}) | |
res.on('error', function(e) { | |
console.error('Error calling external API. '); | |
reject('Error calling external API. '); | |
}); | |
}) | |
}).then(todo => { | |
const data = { | |
title: "I'm changing the title of the todo with id 1 and posting it back to the API as completed", | |
userId: todo.userId, | |
completed: true | |
} | |
const postData = JSON.stringify(data) | |
return new Promise((resolve, reject) => { | |
const req = https.request(postOptions, res => { | |
var body = '' | |
res.on('data', data => { | |
body += data | |
}) | |
res.on('end', () => { | |
const jsonData = JSON.parse(body) | |
resolve(jsonData) | |
}) | |
res.on('error', function(e) { | |
console.error('Error calling external API. '); | |
reject('Error calling external API. '); | |
}) | |
}) | |
// Pass in the modified object back to the API | |
req.write(postData) | |
req.end() | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment