We'll be using the serverless package which makes settings up AWS lambda pretty simple.
Before we begin, make sure you have a AWS account and user created and provide the user programmatic access:
- Use the command: serverless config credentials --provider aws --key userKey --secret userSecret . Replace userKey and userSecret with the appropriate user information you created for the AWS account.
- Use the command serverless create --template aws-nodejs --path folderName . Replace folderName with your choice, this will create a folder with serverless.yml and a file called handler.js
When trying to hook up the functions, we must have a few things:
- Define the functions in the file(handler.js)
- Make sure the available handler is available for the function
hello() which returns the message 'Hi' and bye() which returns the message 'Bye'.
Here's how bye looks like
module.exports.bye = async (event, context, callback) => {
const str = `Bye`;
return str;
}
The event argument contains information about other AWS services the function has gone through, if it went through a load balancer it will contain information about the load balancer. For more information about it, find it here.
The context argument contains information about the invocation, function and environment. For more information about it, find it here.
The callback argument contains information you want to send back in case of success or error, the callback actually accepts two arguments callback(response_error, response_success). Amazon provides documentation on how you should handle async vs sync callbacks here
Make sure both functions are exported. In the .yml file under the functions: section you want to create a section for each.
functions:
hello:
handler: handler.hello
events:
- http:
path: users/hello
method: get
bye:
handler: handler.bye
events:
- http:
path: users/bye
method: get
You'll notice we have the function name, followed by handler: fileName.functionName.To push the code to AWS, we'll have to use the command serverless deploy -v, you'll have to push the code anytime you want the changes reflected on AWS
To call any of the functions to test on command line, use the command serverless invoke -f functionName
To test your app locally, we'll be using serverless-offline package. Once the package has been installed, we have to add the following at the end of serverless.yml:
plugins:
- serverless-offline
Use the command serverless offline start to start it up locally. This uses default port 3000 and you should now be able to get 'Bye' in the terminal or console when you hit the route: localhost:3000/users/bye
This wasn't too bad. Now you can say you have knowledge of cloud based programming!
Source: https://hackernoon.com/a-crash-course-on-serverless-with-node-js-632b37d58b44
No comments:
Post a Comment