本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
构建客户端应用程序
要开始Amazon AppSync在 JavaScript 或 Flow 应用程序中使用,请先将 GraphQL 架构添加到您的项目中。
在构建应用程序之前,您需要安装和配置 npm
要开始使用,请执行以下操作:
-
你需要下载你的架构。
使用 CLI
从您的项目目录中,使用 Amazon CLI 下载您的架构:
aws appsync get-introspection-schema --api-id <api-id> --format SDL schema.graphql --region <region>
使用控制台
转到您的 API 的架构页面。点击下拉按钮,选择导出架构,然后选择
schema.graphql
。将文件保存到您的项目目录中。 -
接下来,使用Amazon Amplify工具链为您的 API 生成代码生成。在项目目录中,运行命令并在需要时按照提示添加 amplify:
npx amplify add codegen --apiId <api-id>
这将生成 GraphQL 文档(查询、变更和订阅),并为您的 JavaScript 或 Flow 应用程序生成类型。如果您修改生成的文档或 API 的架构,则可以随时使用以下方法重新生成客户端代码:
npx amplify codegen
-
最后,创建名为的 API 配置文件
aws-exports.js
并将其放在项目的源目录中。用你的 API 值替换这些值。你可以在 API 的设置页面上找到这些值:const awsmobile = { "aws_appsync_graphqlEndpoint": "<API URL>", "aws_appsync_region": "<REGION>", "aws_appsync_authenticationType": "API_KEY", "aws_appsync_apiKey": "<API KEY>", }; export default awsmobile;
-
现在,您可以更新应用程序以利用您的Amazon AppSync GraphQL API。在你的项目中安装这个
aws-amplify
库以利用它的 API GraphQL 模块:npm install @aws-amplify/api
-
导入Amazon Amplify和代码文件中的 API 模块,以及代码生成器生成的任何所需操作。例如,在项目源代码中添加以下代码,确保
<variables>
替换为特定于代码的变量:// top of file import { API } from '@aws-amplify/api' import config from './aws-exports' import { listSomething } from './graphql/queries' // after your imports API.configure(config) // later down in your code async function list() { const response = await API.graphql({ query: listSomething, variables: { // <your variables, optional> }, }) console.log(response) } list()