aws(学习笔记第四十八课) appsync-graphql-dynamodb

aws(学习笔记第四十八课) appsync-graphql-dynamodb

  • 使用graphql来方便操作dynamodb
  • 理解graphql中的graphql apischemaresolver

学习内容:

  • graphql
  • graphql api
  • schema
  • resolver

1. 代码连接和修改

1.1 代码链接

代码链接(appsync-graphql-dynamodb)

1.2 代码修改

1.2.1 加上必要的depencies

各个resolver创建的时候,都是需要data_source的,所以需要事前将resolverdepencies加上data source

python 复制代码
        get_one_resolver.add_depends_on(data_source)
        get_all_resolver.add_depends_on(data_source)
        save_resolver.add_depends_on(data_source)
        delete_resolver.add_depends_on(data_source)
1.2.2 加上必要的outputs
python 复制代码
        CfnOutput(
            self, "AppSyncApiUrl",
            value=items_graphql_api.attr_graph_ql_url,
            description="AppSync GraphQL API URL"
        )
        CfnOutput(
            self, "AppSyncApiKey",
            value=items_api_key.attr_api_key,  # 假设已定义 items_api_key = CfnApiKey(...)
            description="AppSync API Key"
        )

2. 整体架构

  • 定义一个graphql api
  • 为了安全访问,定义一个api key
  • 定义一个api schema
    • 两个查询apiallget one
    • 定义两个更新apideletesave
  • 定义了一个dynamo table,用来存储数据
  • schema定义了四个resolver
    • all resovler
    • get one resolver
    • save resolver
    • delete resolver

3. 代码详细

3.1 定义api以及api key

python 复制代码
 table_name = 'items'

        items_graphql_api = CfnGraphQLApi(
            self, 'ItemsApi',
            name='items-api',
            authentication_type='API_KEY'
        )

        items_api_key = CfnApiKey(
            self, 'ItemsApiKey',
            api_id=items_graphql_api.attr_api_id
        )

3.2 定义apischema

python 复制代码
 api_schema = CfnGraphQLSchema(
            self, 'ItemsSchema',
            api_id=items_graphql_api.attr_api_id,
            definition=f"""\
                type {table_name} {{
                    {table_name}Id: ID!
                    name: String
                }}
                type Paginated{table_name} {{
                    items: [{table_name}!]!
                    nextToken: String
                }}
                type Query {{
                    all(limit: Int, nextToken: String): Paginated{table_name}!
                    getOne({table_name}Id: ID!): {table_name}
                }}
                type Mutation {{
                    save(name: String!): {table_name}
                    delete({table_name}Id: ID!): {table_name}
                }}
                type Schema {{
                    query: Query
                    mutation: Mutation
                }}"""
        )

3.3 定义dynamoDB table

python 复制代码
 items_table = Table(
            self, 'ItemsTable',
            table_name=table_name,
            partition_key=Attribute(
                name=f'{table_name}Id',
                type=AttributeType.STRING
            ),
            billing_mode=BillingMode.PAY_PER_REQUEST,
            stream=StreamViewType.NEW_IMAGE,

            # The default removal policy is RETAIN, which means that cdk
            # destroy will not attempt to delete the new table, and it will
            # remain in your account until manually deleted. By setting the
            # policy to DESTROY, cdk destroy will delete the table (even if it
            # has data in it)
            removal_policy=RemovalPolicy.DESTROY # NOT recommended for production code
        )

3.4 定义dynamoDB访问的role,以及data source

这里data source,可以看出是将graphql apidynamoDBtable进行关联。

python 复制代码
      items_table_role = Role(
            self, 'ItemsDynamoDBRole',
            assumed_by=ServicePrincipal('appsync.amazonaws.com')
        )

        items_table_role.add_managed_policy(
            ManagedPolicy.from_aws_managed_policy_name(
                'AmazonDynamoDBFullAccess'
            )
        )

        data_source = CfnDataSource(
            self, 'ItemsDataSource',
            api_id=items_graphql_api.attr_api_id,
            name='ItemsDynamoDataSource',
            type='AMAZON_DYNAMODB',
            dynamo_db_config=CfnDataSource.DynamoDBConfigProperty(
                table_name=items_table.table_name,
                aws_region=self.region
            ),
            service_role_arn=items_table_role.role_arn
        )

3.5 定义四个api resolver

3.5.1 get one resolver
python 复制代码
        get_one_resolver = CfnResolver(
            self, 'GetOneQueryResolver',
            api_id=items_graphql_api.attr_api_id,
            type_name='Query',
            field_name='getOne',
            data_source_name=data_source.name,
            request_mapping_template=f"""\
            {{
                "version": "2017-02-28",
                "operation": "GetItem",
                "key": {{
                "{table_name}Id": $util.dynamodb.toDynamoDBJson($ctx.args.{table_name}Id)
                }}
            }}""",
            response_mapping_template="$util.toJson($ctx.result)"
        )
        get_one_resolver.add_depends_on(api_schema)
        get_one_resolver.add_depends_on(data_source)
3.5.2 all resolver
python 复制代码
get_all_resolver = CfnResolver(
            self, 'GetAllQueryResolver',
            api_id=items_graphql_api.attr_api_id,
            type_name='Query',
            field_name='all',
            data_source_name=data_source.name,
            request_mapping_template=f"""\
            {{
                "version": "2017-02-28",
                "operation": "Scan",
                "limit": $util.defaultIfNull($ctx.args.limit, 20),
                "nextToken": $util.toJson($util.defaultIfNullOrEmpty($ctx.args.nextToken, null))
            }}""",
            response_mapping_template="$util.toJson($ctx.result)"
        )

        get_all_resolver.add_depends_on(api_schema)
        get_all_resolver.add_depends_on(data_source)
3.5.3 save resolver
python 复制代码
        save_resolver = CfnResolver(
            self, 'SaveMutationResolver',
            api_id=items_graphql_api.attr_api_id,
            type_name='Mutation',
            field_name='save',
            data_source_name=data_source.name,
            request_mapping_template=f"""\
            {{
                "version": "2017-02-28",
                "operation": "PutItem",
                "key": {{
                    "{table_name}Id": {{ "S": "$util.autoId()" }}
                }},
                "attributeValues": {{
                    "name": $util.dynamodb.toDynamoDBJson($ctx.args.name)
                }}
            }}""",
            response_mapping_template="$util.toJson($ctx.result)"
        )
        save_resolver.add_depends_on(api_schema)
        save_resolver.add_depends_on(data_source)
3.5.4 delete resolver
python 复制代码
        delete_resolver = CfnResolver(
            self, 'DeleteMutationResolver',
            api_id=items_graphql_api.attr_api_id,
            type_name='Mutation',
            field_name='delete',
            data_source_name=data_source.name,
            request_mapping_template=f"""\
            {{
                "version": "2017-02-28",
                "operation": "DeleteItem",
                "key": {{
                "{table_name}Id": $util.dynamodb.toDynamoDBJson($ctx.args.{table_name}Id)
                }}
            }}""",
            response_mapping_template="$util.toJson($ctx.result)"
        )

        delete_resolver.add_depends_on(api_schema)
        delete_resolver.add_depends_on(data_source)
3.5.5 增加outputs

为了能够得到graphql apiendpoint url,还有访问api key,这里进行outputs的输出

python 复制代码
      CfnOutput(
            self, "AppSyncApiUrl",
            value=items_graphql_api.attr_graph_ql_url,
            description="AppSync GraphQL API URL"
        )
        CfnOutput(
            self, "AppSyncApiKey",
            value=items_api_key.attr_api_key,  # 假设已定义 items_api_key = CfnApiKey(...)
            description="AppSync API Key"
        )

4. 执行stack

4.1 执行stack

shell 复制代码
python -m venv ./venv
source .venv/Scripts/activate
pip install -r requirements.txt
cdk --require-approval never deploy

4.2 使用postman进行api调用,更新和查询dynamoDB table

4.2.1 生成GraphQL Request
4.2.2 使用save进行数据做成

authorizationtab上进行api key的设定。

指定完毕,可以看到生成的数据中,已经生成了itemsID

4.2.3 使用all进行数据查询

5. 及时cleanup

相关推荐
陈橘又青9 分钟前
开创性的初创企业利用 Amazon SageMaker孵化器释放企业价值
人工智能·网络协议·学习·ai·编辑器
宵时待雨15 分钟前
C语言笔记归纳21:编译与链接
linux·c语言·开发语言·笔记
走在路上的菜鸟18 分钟前
Android学Dart学习笔记第二十二节 类-扩展方法
android·笔记·学习·flutter
TL滕23 分钟前
从0开始学算法——第二十天(简易搜索引擎)
笔记·学习·算法
你好~每一天32 分钟前
数据分析专员:当传统汽车销售融入AI智能,如何驱动业绩新增长
大数据·数据结构·人工智能·学习·数据分析·汽车·高性价比
✎ ﹏梦醒͜ღ҉繁华落℘34 分钟前
计算机网络学习(三)-- IP地址 和 MAC 地址如何转换,以太网
学习·tcp/ip·计算机网络
铭哥的编程日记1 小时前
后端面试通关笔记:从真题到思路(me)
笔记·面试·职场和发展
秦奈1 小时前
Unity复习学习笔记(七):NGUI
笔记·学习·unity
行业探路者1 小时前
网站二维码的全解析与使用技巧分享
大数据·人工智能·学习·产品运营·软件工程
晨欣1 小时前
[eBPF硬核] Gemini阿吉学习笔记:Tetragon企业版两类核心日志 & 冷热数据分流架构设计 & 学习资源推荐
笔记·学习·云原生·云安全·ebpf·谷歌gemini