From 6055fa3c445d0f342dcd5c0aafa0cdaf5aa4d433 Mon Sep 17 00:00:00 2001 From: Yusuke Wada Date: Wed, 7 Mar 2018 14:51:48 +0900 Subject: [PATCH] [add] hero get function. --- buildspec.yml | 3 -- environments/sam-local.json | 4 ++ src/functions/heroes/index.py | 46 ++++++++----------- template_heroes.yaml | 38 ++++++++++++++- .../heroes/examples/get_payload.json | 2 +- .../heroes/examples/put_payload.json | 4 ++ test/functions/heroes/integration.bats | 20 +++++++- 7 files changed, 83 insertions(+), 34 deletions(-) create mode 100644 test/functions/heroes/examples/put_payload.json diff --git a/buildspec.yml b/buildspec.yml index 53993d2..6bf168d 100644 --- a/buildspec.yml +++ b/buildspec.yml @@ -9,7 +9,6 @@ phases: commands: - sudo apt-get update - sudo apt-get install zip - - alias md5='md5sum' - sudo curl -o /usr/local/bin/jq -L https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64 && sudo chmod +x /usr/local/bin/jq - curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash - - sudo apt-get install -y nodejs @@ -40,7 +39,5 @@ phases: post_build: commands: - ./deploy.sh -# - aws s3 sync dist s3://vote-uploader/site --delete # 1 -# - aws cloudfront create-invalidation --distribution-id ${CLOUDFRONT_DISTRIBUTION_ID} --paths '/*' # 2 diff --git a/environments/sam-local.json b/environments/sam-local.json index 340a4a5..df7adfc 100644 --- a/environments/sam-local.json +++ b/environments/sam-local.json @@ -2,5 +2,9 @@ "GetHeroes": { "DYNAMODB_ENDPOINT": "http://localstack:4569/", "HERO_TABLE_NAME": "CM-Heroes" + }, + "PutHeroes": { + "DYNAMODB_ENDPOINT": "http://localstack:4569/", + "HERO_TABLE_NAME": "CM-Heroes" } } \ No newline at end of file diff --git a/src/functions/heroes/index.py b/src/functions/heroes/index.py index 139a38b..6d0cd15 100644 --- a/src/functions/heroes/index.py +++ b/src/functions/heroes/index.py @@ -1,15 +1,14 @@ """This is python3.6 program.""" -import json import boto3 import datetime -from boto3.dynamodb.conditions import Key, Attr +import uuid from builtins import Exception import os from src.functions.heroes.utils import * -DYNAMODB_ENDPOINT = os.environ['DYNAMODB_ENDPOINT'] -HERO_TABLE_NAME = os.environ['HERO_TABLE_NAME'] +DYNAMODB_ENDPOINT = os.getenv('DYNAMODB_ENDPOINT') +HERO_TABLE_NAME = os.getenv('HERO_TABLE_NAME') print(DYNAMODB_ENDPOINT) print(HERO_TABLE_NAME) @@ -22,44 +21,39 @@ DYNAMODB_TABLE = DYNAMO.Table(HERO_TABLE_NAME) -# HERO_TABLE = DYNAMO.Table(TABLE_NAME) - - -# DynamoDB def get(event, context): try: # get DeviceSerialID hero_id = event['id'] - print("Received event: " + json.dumps(event, indent=2)) + response = DYNAMODB_TABLE.get_item( + Key={ + 'id': hero_id + } + ) - # return {'statusCode': 200, 'body': "Hello " + json.dumps(event['body']),'headers': {'Content-Type': 'application/json'}} + return response - # response = DYNAMO.query( - # TableName='CM-Heroes', - # KeyConditionExpression=Key('id').eq(hero_id) - # ) + except Exception as error: + raise error - # response = DYNAMODB_TABLE.get_item( - # Key={ - # 'id': '1' - # } - # ) - print('start') +def put(event, context): + try: + hero_id = str(uuid.uuid4()) + name = event.get('name') + office = event.get('office') updated_at = epoc_by_second_precision(datetime.now()) response = DYNAMODB_TABLE.put_item( Item={ - 'id': '1', + 'id': hero_id, + 'name': name, + 'office': office, 'updated_at': updated_at, 'created_at': updated_at, - 'modified_at': updated_at } ) - - print('end') return response - except Exception as error: - raise error + raise error \ No newline at end of file diff --git a/template_heroes.yaml b/template_heroes.yaml index 31cd518..16e99ad 100644 --- a/template_heroes.yaml +++ b/template_heroes.yaml @@ -18,11 +18,45 @@ Parameters: Type: String Default: api_backend/0000.zip Resources: + CM-HeroesTable: + Type: AWS::DynamoDB::Table + Properties: + TableName: !Ref HeroTableName + AttributeDefinitions: + - AttributeName: id + AttributeType: S + KeySchema: + - AttributeName: id + KeyType: HASH + ProvisionedThroughput: + ReadCapacityUnits: 5 + WriteCapacityUnits: 5 GetHeroes: Type: AWS::Serverless::Function Properties: + FunctionName: heroes-GetHeroes Handler: src/functions/heroes/index.get Runtime: python3.6 + CodeUri: + Bucket: !Ref BucketName + Key: !Ref CodeKey + Policies: AmazonDynamoDBReadOnlyAccess + Environment: + Variables: + DYNAMODB_ENDPOINT: !Ref DynamoDBEndpoint + HERO_TABLE_NAME: !Ref HeroTableName + Events: + GetResource: + Type: Api + Properties: + Path: /heroes/{heroId} + Method: get + PutHeroes: + FunctionName: heroes-PutHeroes + Type: AWS::Serverless::Function + Properties: + Handler: src/functions/heroes/index.put + Runtime: python3.6 CodeUri: Bucket: !Ref BucketName Key: !Ref CodeKey @@ -35,5 +69,5 @@ Resources: GetResource: Type: Api Properties: - Path: /resource/{heroId} - Method: get \ No newline at end of file + Path: /heroes + Method: put \ No newline at end of file diff --git a/test/functions/heroes/examples/get_payload.json b/test/functions/heroes/examples/get_payload.json index 3d5f7c2..ef70972 100644 --- a/test/functions/heroes/examples/get_payload.json +++ b/test/functions/heroes/examples/get_payload.json @@ -52,5 +52,5 @@ "stageVariables": { "baz": "qux" }, - "id": "1" + "id": "test-id" } \ No newline at end of file diff --git a/test/functions/heroes/examples/put_payload.json b/test/functions/heroes/examples/put_payload.json new file mode 100644 index 0000000..00d4c72 --- /dev/null +++ b/test/functions/heroes/examples/put_payload.json @@ -0,0 +1,4 @@ +{ + "name": "Bubble-man", + "office": "Tokyo" +} \ No newline at end of file diff --git a/test/functions/heroes/integration.bats b/test/functions/heroes/integration.bats index 98445f8..5afc933 100644 --- a/test/functions/heroes/integration.bats +++ b/test/functions/heroes/integration.bats @@ -11,8 +11,24 @@ teardown() { echo "teardown" } +@test "DynamoDB Get Funciton response the correct item" { + data='{ + "id": {"S": "test-id"}, + "name": {"S": "Test-man"}, + "created_at": {"N": "1520400553"}, + "updated_at": {"N": "1520400554"}, + "office": {"S": "virtual"} }' + + expected=`echo "${data}" | jq -r .` + + aws --endpoint-url=http://localhost:4569 dynamodb put-item --table-name CM-Heroes --item "${data}" + + result=`sam local invoke --docker-network ${docker_network_id} -t template_heroes.yaml --event test/functions/heroes/examples/get_payload.json --env-vars environments/sam-local.json GetHeroes | jq -r .Item` + + [ $result -eq $expected ] +} + @test "DynamoDB PUT Funciton response code is 200" { - echo $docker_network_id - result=`sam local invoke --docker-network ${docker_network_id} -t template_heroes.yaml --event test/functions/heroes/examples/get_payload.json --env-vars environments/sam-local.json GetHeroes | jq '.ResponseMetadata.HTTPStatusCode'` + result=`sam local invoke --docker-network a27c0476cb8e -t template_heroes.yaml --event test/functions/heroes/examples/put_payload.json --env-vars environments/sam-local.json PutHeroes | jq '.ResponseMetadata.HTTPStatusCode'` [ $result -eq 200 ] }