queirozsc
8/30/2017 - 5:41 PM

Building a Simple Application Using SAM Local http://docs.aws.amazon.com/lambda/latest/dg/test-sam-local.html

Building a Simple Application Using SAM Local http://docs.aws.amazon.com/lambda/latest/dg/test-sam-local.html

aws cloudformation deploy \
   --template-file serverless-output.yaml \
   --stack-name bnpStackProduct \
   --capabilities CAPABILITY_IAM
aws cloudformation package \
   --template-file template.yaml \
   --output-template-file serverless-output.yaml \
   --s3-bucket lambda.buildnprice.io
aws s3 mb s3://lambda.buildnprice.io --region us-east-1
sam local start-api --env-vars env.json
{
  "MyFunction1": {
    "TABLE_NAME": "localtable",
    "BUCKET_NAME": "testBucket"
  },
  "MyFunction2": {
    "TABLE_NAME": "localtable",
    "STAGE": "dev"
  },
}
sam local invoke --log-file ./output.log
curl -XDELETE http://localhost:3000/products/1
curl http://localhost:3000/products 
'use strict';

exports.handler = (event, context, callback) => {

    let id = event.pathParameters.product || false;
    switch(event.httpMethod){

        case "GET":

            if(id) {
                callback(null, {body: "This is a READ operation on product ID " + id});
                return;  
            } 

            callback(null, {body: "This is a LIST operation, return all products"});
            break;

        case "POST":            
            callback(null, {body: "This is a CREATE operation"}); 
            break;

        case "PUT": 
            callback(null, {body: "This is an UPDATE operation on product ID " + id});
            break;

        case "DELETE": 
            callback(null, {body:"This is a DELETE operation on product ID " + id});
            break;

        default:
            // Send HTTP 501: Not Implemented
            console.log("Error: unsupported HTTP method (" + event.httpMethod + ")");
            callback(null, { statusCode: 501 })

    }

}
AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: My first serverless application.

Resources:

  Products:
    Type: AWS::Serverless::Function
    Properties:
      Handler: products.handler
      Runtime: nodejs6.10
      Events:
        ListProducts:
          Type: Api
          Properties:
            Path: /products
            Method: get
        CreateProduct:
          Type: Api
          Properties:
            Path: /products
            Method: post
        Product:
          Type: Api
          Properties:
            Path: /products/{product}
            Method: any
npm install -g aws-sam-local