Closed3

サブスク通知LineBotのサブスク登録にLIFFを利用してみた

yorosuyorosu

S3静的ホスティングからAPIGatewayのAPIを呼ぶ

基本的なやり方はこちらの記事を参照した

https://qiita.com/dnpds-yuharagi/items/e2baffe823777b5421a6

CORS関連で色々ハマったので以下のようにメモを残す

前の記事

https://zenn.dev/yorosu/scraps/80a97cd4e9a369

S3

以下の記事のS3のCORSについての設定を行う

Refs

https://qiita.com/dnpds-yuharagi/items/e2baffe823777b5421a6

API Gateway

  1. CORSを作成

  1. レスポンスメソッドを追加

Refs

https://dev.classmethod.jp/articles/apigateway-lambda-proxy-cors/

https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/how-to-cors.html

Lambda (Server)

ここがポイント

    return {
        'statusCode': 200,
        'headers': { 
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Content-Type"
        },
        'body': json.dumps(item,default=decimal_default_proc)
    }

全コードはこちら

lambda_function.py
import logging

import boto3
import json
from decimal import Decimal

# define the DynamoDB table that Lambda will connect to
tableName = 'subs_in_use_table'

# create the DynamoDB resource
dynamo = boto3.resource('dynamodb').Table(tableName)

print('Loading function')

def lambda_handler(event, context):
    '''Provide an event that contains the following keys:

      - operation: one of the operations in the operations dict below
      - payload: a JSON object containing parameters to pass to the 
                 operation being performed
    '''

    #Decimal型の場合はint型に変換
    def decimal_default_proc(obj):
        if isinstance(obj, Decimal):
            return int(obj)
        raise TypeError

    # define the functions used to perform the CRUD operations
    def ddb_create(x):
        dynamo.put_item(**x)
        return {
            'statusCode': 200,
            'headers': { 
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Headers": "Content-Type"
            },
            'body': json.dumps({'message': 'Item created successfully'})
        }

    def ddb_read(x):
        response = dynamo.get_item(**x)
        if 'Item' in response:
            item = response['Item']
            return {
                'statusCode': 200,
                'headers': { 
                    "Access-Control-Allow-Origin": "*",
                    "Access-Control-Allow-Headers": "Content-Type"
                },
                'body': json.dumps(item,default=decimal_default_proc)
            }
        else:
            return {
                'statusCode': 404,
                'headers': { 
                    "Access-Control-Allow-Origin": "*",
                    "Access-Control-Allow-Headers": "Content-Type"
                },
                'body': json.dumps({'message': 'Item not found'})
            }

    def ddb_update(x):
        dynamo.update_item(**x)
        return {
            'statusCode': 200,
            'headers': { 
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Headers": "Content-Type"
            },            
            'body': json.dumps({'message': 'Item updated successfully'})
        }

        
    def ddb_delete(x):
        dynamo.delete_item(**x)
        return {
            'statusCode': 200,
            'headers': { 
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Headers": "Content-Type"
            },
            'body': json.dumps({'message': 'Item deleted successfully'})
        }

    def ddb_scan():
        response = dynamo.scan()
        print(response)
        if 'Items' in response:
            items = response['Items']
            return {
                'statusCode': 200,
                'headers': { 
                    "Access-Control-Allow-Origin": "*",
                    "Access-Control-Allow-Headers": "Content-Type"
                },
                'body': json.dumps(items,default=decimal_default_proc)
            }
        else:
            return {
                'statusCode': 404,
                'headers': { 
                    "Access-Control-Allow-Origin": "*",
                    "Access-Control-Allow-Headers": "Content-Type"
                },                
                'body': json.dumps({'message': 'Item not found'})
            }    
    
    print("Event:", event)

    operations = {
        'GET': ddb_scan,
        'POST': {
            'read': ddb_read,
            'create': ddb_create
        },
        'PUT': {
            'update': ddb_update
        },
        'DELETE': {
            'delete': ddb_delete
        }
    }
    
    httpMethod = event['httpMethod']
    
    if httpMethod == 'GET':
        return operations[httpMethod]()
    else:
        event_body = json.loads(event['body'])
        operation = event_body['operation']
        if operation in operations[httpMethod]:
            return operations[httpMethod][operation](event_body.get('payload'))
        else:
            raise ValueError('Unrecognized operation "{}"'.format(operation))

Refs

https://dev.classmethod.jp/articles/apigateway-lambda-proxy-cors/

HTML, JS

https://github.com/Yorosu-10/sabusukukikuyo_register

このスクラップは2024/05/28にクローズされました