在AWS Amplify中使用AppSync和多个DynamoDB表格的解决方法如下:
npm install -g @aws-amplify/cli
amplify configure
amplify init
amplify add api
选择GraphQL类型,并按照提示设置API名称、身份验证方式等。
amplify add storage
选择DynamoDB类型,并按照提示设置表格名称、主键等。
amplify add api
选择GraphQL类型,并在"Provide API name"处输入之前创建的AppSync API名称。
amplify/backend/api/{API名称}/schema.graphql文件中定义数据模型和关联,例如:type Post @model {
id: ID!
title: String!
content: String!
comments: [Comment] @connection
}
type Comment @model {
id: ID!
content: String!
post: Post @connection
}
这将定义一个Post类型和一个Comment类型,其中Post具有一个comments字段,表示与Comment类型的关联。
amplify push
这将部署AppSync API和DynamoDB表格。
import Amplify, { API, graphqlOperation } from 'aws-amplify';
import { createPost } from './graphql/mutations';
import { listPosts } from './graphql/queries';
Amplify.configure({
aws_appsync_graphqlEndpoint: 'YOUR_APPSYNC_API_ENDPOINT',
aws_appsync_region: 'YOUR_APPSYNC_API_REGION',
aws_appsync_authenticationType: 'API_KEY',
aws_appsync_apiKey: 'YOUR_APPSYNC_API_KEY',
});
// 创建一个新的Post
const newPost = { title: 'My First Post', content: 'Hello World!' };
API.graphql(graphqlOperation(createPost, { input: newPost }));
// 获取所有的Post
API.graphql(graphqlOperation(listPosts)).then((result) => {
const posts = result.data.listPosts.items;
console.log(posts);
});
在Amplify.configure中,替换YOUR_APPSYNC_API_ENDPOINT、YOUR_APPSYNC_API_REGION和YOUR_APPSYNC_API_KEY为你的AppSync API的相关信息。
这样,你就可以使用AWS Amplify、AppSync和多个DynamoDB表格来构建你的应用程序了。