当前位置: 首页 > news >正文

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

        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
        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

 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

 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: Querymutation: Mutation}}""")

在这里插入图片描述

3.3 定义dynamoDB table

 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进行关联。

      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
        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
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
        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
        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的输出

      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

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

http://www.lryc.cn/news/576715.html

相关文章:

  • Docker错误问题解决方法
  • Keil MDK 的 STM32 开发问题:重定向 printf 函数效果不生效(Keil MDK 中标准库未正确链接)
  • 基于springboot+vue的数字科技风险报告管理系统
  • 现代 JavaScript (ES6+) 入门到实战(一):告别 var!拥抱 let 与 const,彻底搞懂作用域
  • 领域驱动设计(DDD)【23】之泛化:从概念到实践
  • 网络缓冲区
  • DOP数据开放平台(真实线上项目)
  • 马斯克的 Neuralink:当意念突破肉体的边界,未来已来
  • Word之电子章制作——1
  • 【编译原理】期末
  • 华为云Flexus+DeepSeek征文|利用华为云一键部署的Dify平台构建高效智能电商客服系统实战
  • Youtube双塔模型
  • C++共享型智能指针std::shared_ptr使用介绍
  • cocos creator 3.8 - 精品源码 - 挪车超人(挪车消消乐)
  • Neo4j无法建立到 localhost:7474 服务器的连接出现404错误
  • Linux基本命令篇 —— less命令
  • springboot+Vue驾校管理系统
  • matplotlib 绘制水平柱状图
  • 基于LQR控制器的六自由度四旋翼无人机模型simulink建模与仿真
  • 使用deepseek制作“喝什么奶茶”随机抽签小网页
  • 我的世界模组开发进阶教程——机械动力的数据生成(2)
  • 【C++进阶】--- 继承
  • 基于WOA鲸鱼优化算法的圆柱体容器最大体积优化设计matlab仿真
  • 人大金仓数据库jdbc连接jar包kingbase8-8.6.0.jar驱动包最新版下载(不需要积分)
  • C++泛型编程2 - 类模板
  • C# 委托(为委托添加方法和从委托移除方法)
  • 13-StringBuilder类的使用
  • Linux内核网络协议栈深度解析:面向连接的INET套接字实现
  • 8. 【Vue实战--孢子记账--Web 版开发】-- 账户账本管理
  • Uni-App 小程序面试题高频问答汇总