This is the code used the article Automated SMS notifications with AWS Lambda and Twilio APIs published on Twilio's blog
Here follows a detailed description of every part of the code:
- The first thing we do is to import the
request-promise-native
library. - Then we declare our handler function by respecting the expected signature with
event
,context
andcallback
as described previously. - Inside the handler, we define some constants that we will use as configuration in the rest of the code. Be sure to fill in all the values that are specific to your account.
- At this point we are ready to perform the first API request to get the exchange rate from Fixer.io.
- Since
request-promise-native
returns a promise, we have to write a then and acatch
method to handle the asynchronous control flow. Inside the then we have get the response data from the API call and we can use it to extract the current exchange rate. We also log the result, which is a good debug practice. - Now we are ready to send the exchange rate to our mobile number using the Twilio API. We do this by using again request-promise-native. This time it’s a POST request and we need to provide the authentication and SMS details as we discussed above.
- Again, we have to deal with a promise, so we have to attach another then function to the chain of promises. Notice that in the previous step we used return with the result of the request. This allowed us to propagate the promise in the chain, so that we can share a single
catch
to handle errors and deal with every asynchronous step with dedicatedthen
hooks. In this last then hook, we just need to log the result and invoke the callback to complete the execution of the Lambda. - At the end of the promise chain we have our generic catch hook. It will be invoked only if any of the promises in the chain rejects (fails). In this case we can only log the error and terminate the execution of the lambda by invoking the callback and propagating the error to AWS by passing it as first parameter to the callback. This will mark the execution as failed.
- The last thing we need to do is to export our handler function so that it can be loaded by the AWS runtime. We name the export handler, so that we can later reference this function as index.handler.