Serverless configuration

In order to use Serverless with our AWS Account, we will need to set up our credentials on the command line. This step will require the information that we downloaded when we created our AWS user with programmatic access, in particular the API Access key ID, and the Secret access key.

To set up Serverless with our AWS credentials, execute the following on the command line:

serverless config credentials --provider aws --key <insert access key> --secret <insert secret key>  

Here, we have specified configuration options for the credentials that Serverless will use to access the AWS API. The options that we have specified include aws as the API provider, as well as the API Access Key ID and Secret access key.

Once this step is complete, Serverless will store these credentials for subsequent use.

We can now create a standard Serverless template for an AWS Lambda function by executing the following on the command line:

serverless create --template aws-nodejs --path serverless-sample  

This will create a new directory named serverless-sample, and within it, a serverless.yml file and a hander.js file. Let's first take a look at the generated handler.js file, as follows:

'use strict'; 
 
module.exports.hello = async (event, context) => { 
  return { 
    statusCode: 200, 
    body: JSON.stringify({ 
      message: 'Go Serverless v1.0! Your function executed 
         successfully!', 
      input: event, 
    }), 
  }; 
 
}; 

Here, we have a JavaScript file that uses the module.exports property to expose a function named hello, as seen in the use of module.exports.hello =. This function is the AWS Lambda function itself, and is defined as an async function that has two parameters, named event and context. The event and context parameters are filled in by AWS in order to pass information from the API resource to the Lambda function. The body of the function returns a JavaScript object that has a statusCode and a body property. This object represents a standard HTTP response, and the statusCode property is the HTTP return code. In this example our HTTP request will return a 200, OK response. The body property contains a message property, as well as an input property.

Note how closely this code resembles an Express handler. Aside from the event and context parameters, both the Express handlers and our AWS Lambda handlers both attach a function to module.exports, and both return HTTP responses.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.6.75