aws api_带有AWS的GraphQL API和与React一起使用

aws api

GraphQL has become a go-to API implementation for developers looking to take advantage of features liketype safety, network efficiency, real-time data with subscriptions & more.

GraphQL已成为寻求利用类型安全,网络效率,带有订阅的实时数据等功能的开发人员的首选API实现。

Building, managing, & deploying your own GraphQL server can be tedious & time consuming, especially for developers new to the technology that may want to quickly get a real-world, secure & scalable GraphQL API up and running without having to learn how to create it from scratch (as well as spend the time learning best practices around API design & authorization).

构建,管理和部署您自己的GraphQL服务器可能是繁琐且耗时的,特别是对于刚接触该技术的开发人员而言,他们可能想快速地启动并运行真实,安全和可扩展的GraphQL API,而无需学习如何创建从头开始(以及花时间学习有关API设计和授权的最佳实践)。

推出AWS AppSync (Introducing AWS AppSync)

In this post we'll learn how to use AWS AppSync, a fully managed GraphQL service, to create a serverless GraphQL API. AWS AppSync allows developers to quickly create serverless, scalable & secure GraphQL APIs.

在本文中,我们将学习如何使用AWS AppSync (一种完全托管的GraphQL服务)来创建无服务器的GraphQL API。 AWS AppSync使开发人员可以快速创建无服务器,可扩展且安全的GraphQL API。

我们将经历: (We'll go through:)

  • how to create a new GraphQL API

    如何创建一个新的GraphQL API
  • how to interact with it in the AWS console

    如何在AWS控制台中与其进行交互
  • how to access the API from a React application

    如何从React应用程序访问API

我们的CLI工具:AWS Amplify (Our CLI Tool: AWS Amplify)

We'll be using AWS Amplify to create the AppSync service & connect to it from our React application. AWS Amplify is a CLI & Client toolchain that allows developers to create AWS services from their front-end environment & connect to them from the client-side applications.

我们将使用AWS Amplify创建AppSync服务并从我们的React应用程序连接到它。 AWS Amplify是一个CLI&Client工具链,它使开发人员可以从前端环境创建AWS服务,并从客户端应用程序连接至它们。

The app that we will be building is a restaurant tracker app that will allow us to keep up with all of the restaurants we would like to visit as well as store information about each restaurant. We'll use React as the front-end for the application.

我们将要构建的应用程序是一个餐厅跟踪器应用程序 ,它将使我们能够跟上我们要访问的所有餐厅以及每个餐厅的商店信息。 我们将使用React作为应用程序的前端。

入门 ( Getting Started )

The AWS Amplify CLI is the tool that we will be using to create the AWS AppSync API. This CLI allows us to create & deploy AWS services directly from the command line. The services that we will be creating are AWS AppSync for the API layer & Amazon Cognito for the authentication provider.

AWS Amplify CLI是我们将用来创建AWS AppSync API的工具。 此CLI允许我们直接从命令行创建和部署AWS服务。 我们将创建的服务是用于API层的AWS AppSync和用于身份验证提供程序的Amazon Cognito。

应用功能 (App Features)

Users will be able to sign up for an account, sign in to the account, create a restaurant, & query for only the restaurants that the user created.

用户将能够注册一个帐户,登录该帐户,创建一个餐厅,并仅查询该用户创建的餐厅。

创建React应用 (Creating the React App)

First, we'll create the React application that we'll be using to connect to our API. To do so, we'll use Create React App:

首先,我们将创建用于连接到API的React应用程序。 为此,我们将使用Create React App:

create-react-app restaurant-app# or
npx create-react-app restaurant-app

Once the app is created, we'll change into the new directory & install aws-amplify:

创建应用程序后,我们将转到新目录并安装aws-amplify:

cd restaurant-app
npm install aws-amplify

放大CLI ( Amplify CLI )

The next thing we need to do is install & configure the AWS Amplify CLI. To do so, we'll use npm:

我们需要做的下一件事是安装和配置AWS Amplify CLI。 为此,我们将使用npm:

npm install -g @aws-amplify/cli

Once the CLI is installed, we'll need to configure it to use an IAM user from our AWS account

安装CLI后,我们需要对其进行配置,以使用我们AWS账户中的IAM用户

amplify configure

If you'd like a video walkthrough of how to install & configure the AWS Amplify CLI, click here. Now that the CLI is installed & configured, we can initialize a new Amplify project in our React application. From the inside your React application, run the following command:

如果您想获得有关如何安装和配置AWS Amplify CLI的视频演练,请单击此处 。 现在已经安装和配置了CLI,我们可以在React应用程序中初始化一个新的Amplify项目。 在您的React应用程序内部,运行以下命令:

amplify init
amplify init

Here, you will be prompted with questions about your application configuration. You can choose your default text editor and the defaults for all of the other options.

在这里,将提示您有关应用程序配置的问题。 您可以选择默认的文本编辑器以及所有其他选项的默认设置。

Once the project has been initialized, we can go ahead and add an an API & authentication to our app. To do so, we'll first add authentication.

初始化项目后,我们可以继续向我们的应用添加API和身份验证。 为此,我们将首先添加身份验证。

添加AWS AppSync API (Adding the AWS AppSync API)

To add the AWS AppSync api, we can run the following command:

要添加AWS AppSync api,我们可以运行以下命令:

amplify add api

Now, you'll be prompted for the following:

现在,系统将提示您输入以下内容:

  • Please select from one of the below mentioned services: GraphQL

    请从下列服务之一中选择: GraphQL

  • Provide API name: restaurantapi (or whatever name you'd like)

    提供API名称: restaurantapi (或您想要的任何名称)

  • Choose an authorization type for the API: API key

    选择API的授权类型: API密钥

  • Do you have an annotated GraphQL schema: N

    您是否有带注释的GraphQL模式: N

  • Do you want a guided schema creation: Y

    您是否需要引导式架构创建:

  • What best describes your project: Single object with fields

    什么最能描述您的项目: 带字段的单个对象

Update the schema to this & save the file:

将架构更新为此并保存文件:

type Restaurant @model {
  id : ID !
  name : String !
  description : String
}

Next, we'll run the push command to create the services in our account:

接下来,我们将运行push命令在我们的帐户中创建服务:

amplify push

Now, you'll be prompted for the following:

现在,系统将提示您输入以下内容:

  • Do you want to generate code for your newly created GraphQL API? Y

    您是否要为新创建的GraphQL API生成代码? ÿ

  • Choose the code generation language target: JavaScript

    选择代码生成语言目标: JavaScript

  • Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/*/.js

    输入graphql查询,变异和订阅的文件名模式: src / graphql / * /.js

  • Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions: Y

    您是否要生成/更新所有可能的GraphQL操作-查询,变异和订阅:

Once the push is complete, the AWS AppSync service have been successfully created in our account.

推送完成后,便已在我们的帐户中成功创建了AWS AppSync服务。

What exactly has been created? If you notice, in the above schema definition, we have an @model directive on the schema type definition. This is part of the Amplify GraphQL Transform library.

究竟创建了什么? 如果您注意到,在以上架构定义中,我们在架构类型定义上有一个@model指令。 这是Amplify GraphQL Transform库的一部分

The library will recognize this directive & automcatically expand the schema into additional schema that is typically necessary for a robust API, including queries, mutations, subscriptions, resolvers & a data source (Amazon DynamoDB). Everything you need to get up & running is now set up for you using this directive.

该库将识别该指令,并自动将模式扩展为强大API通常必需的其他模式,包括查询,突变,订阅,解析器和数据源(Amazon DynamoDB)。 现在,您可以使用此指令为您设置和运行所需的一切。

If at any time you would like to view the services that have been created in your Amplify configuration, you can run amplify status.

如果您想随时查看在Amplify配置中创建的服务,则可以运行Amplify amplify status

To view the AWS AppSync console & see the API that was just created, click here. To view the Cognito user pool that was just created, click here.

要查看AWS AppSync控制台并查看刚刚创建的API,请单击此处 。 要查看刚刚创建的Cognito用户池,请单击此处

Make sure that you are in the same region in which you created your resource by viewing the region in the top right corner of the AWS console.

通过查看AWS控制台右上角的区域,确保您与创建资源的区域相同。

在AWS控制台中测试API ( Testing the API in the AWS Console )

Now that the API has been created, we can go to the AWS AppSync console & begin testing it out! To do so, visit the AWS AppSync console (be sure you are in the correct region), & click on the API name you just created.

现在已经创建了API,我们可以转到AWS AppSync控制台并开始对其进行测试! 为此,请访问AWS AppSync控制台 (确保您位于正确的区域中),然后单击刚刚创建的API名称。

In the left hand menu, you will see links for your data source, settings, schema, & queries. Feel free to click around here & explore.

在左侧菜单中,您将看到数据源,设置,架构和查询的链接。 随时单击此处并进行探索。

What we'd like to do next though is execute mutations & queries against the API. In the left hand menu, click on Queries & try out the following mutation in the query editor:

我们接下来要做的是针对API执行变体和查询。 在左侧菜单中,单击查询 ,然后在查询编辑器中尝试以下突变:

mutation create {
  createRestaurant ( input : {
    name : "Soi"
    description : "Great Thai in Seattle"
  } ) {
    id name d
  }
}

Creating a query in the AWS Console

在AWS控制台中创建查询

Create a couple of mutations & then we'll query for them using the following query:

创建几个突变,然后我们将使用以下查询来查询它们:

query list {
  listRestaurants {
    items {
      id
      name
      description
    }
  }
}

This query should return an array of restaurans showing the id, name & description for each item created.

该查询应返回一个restaurans数组,其中显示了所创建的每个商品的ID,名称和说明。

You may be wondering where the ID comes from, since all we did was pass in a name & description. The ids are automatically generated by the service (in the resolver mapping template) so you don't have to pass them in. If you'd like to view the mapping template for any resolver, click on Schema in the left menu, look for the resolver you'd like to view in the resolvers panel on the right.

您可能想知道ID的来源,因为我们所做的只是输入名称和描述。 这些ID由服务自动生成(在解析器映射模板中),因此您不必传递它们。如果要查看任何解析器的映射模板,请单击左侧菜单中的Schema ,查找您要在右侧的“解析器”面板中查看的解析器。

与React集成 ( Integration with React )

Now that the services are created, we can wire them up with our React application & begin interacting with them.

现在已经创建了服务,我们可以将它们与React应用程序连接起来并开始与它们进行交互。

The first thing we'll do is configure the application with our Amplify resources. To configure the React application, open index.js & add the following three lines of code:

我们要做的第一件事是使用Amplify资源配置应用程序。 要配置React应用程序,请打开indexjs并添加以下三行代码:

import Amplify from 'aws-amplify'
import config from './aws-exports'
Amplify . configure ( config )

Next, open App.js. Here, we'll query for the restaurants & display them in our app. To do so, we'll need to do 5 things:

接下来,打开Appjs 。 在这里,我们将查询餐厅并将其显示在我们的应用中。 为此,我们需要做5件事:

  1. Import the APIs from AWS Amplify

    从AWS Amplify导入API
  2. Import the query definition

    导入查询定义
  3. Create initial state to hold the restaurants array

    创建初始状态以容纳餐厅数组
  4. Query for the restaurants array from our API & update the state

    从我们的API查询餐厅数组并更新状态
  5. Display the restaurants array in the React application.

    在React应用程序中显示restaurant数组。

First, we'll take care of our imports:

首先,我们将照顾进口:

import { API , graphqlOperation } from 'aws-amplify'
import { listRestaurants } from './graphql/queries'

Next, in the class definition, we'll go ahead & create the state & initialize the query in componentDidMount lifecycle method:

接下来,在类定义中,我们将继续并创建状态并在componentDidMount生命周期方法中初始化查询:

state = { restaurants : [ ] }
async componentDidMount ( ) {
  try {
    const apiData = await API . graphql ( graphqlOperation ( listRestaurants ) )
    const restaurants = apiData . data . listRestaurants . items
    this . setState ( { restaurants } )
  } catch ( err ) {
    console . log ( 'error: ' , err )
  }
}

In componentDidMount we fetch the data from the AppSync API by using the API class, calling API.graphql passing in the graphqlOperation helper & the query definition. We the store the data in the restaurants array after it has returned from the array & reset the state.

componentDidMount中,我们通过使用API​​类,调用API.graphql并通过graphqlOperation帮助器和查询定义来从AppSync API中获取数据。 从数组返回数据后,我们将数据存储在restaurants数组中并重置状态。

Now, the data is stored in the state & we can render it to our screen. Let's update the render method to show the restaurant data in our UI:

现在,数据存储在状态中,我们可以将其渲染到屏幕上。 让我们更新render方法以在我们的UI中显示餐厅数据:

// rest of class omitted
render ( ) {
    return (
      < div className = "App" >
        {
          this . state . restaurants . map ( ( rest , i ) => (
            < div style = { styles . item } >
              < p style = { styles . name } > { rest . name } < / p >
              < p style = { styles . description } > { rest . description } < / p >
            < / div >
          ) )
        }
      < / div >
    ) ;
  }
}

const styles = {
  item : {
    padding : 10 ,
    borderBottom : '2px solid #ddd'
  } ,
  name : { fontSize : 22 } ,
  description : { color : 'rgba(0, 0, 0, .45)' }
}

For the final gist of all of the code for this component, check out this link.

有关此组件的所有代码的最终要点,请查看链接。

Now, we should be able to run the app & see the queried data rendered to our screen:

现在,我们应该能够运行该应用程序并查看呈现到屏幕的查询数据:

npm start

GraphQL突变 ( GraphQL Mutations )

Now that we know how to query for data, let's look at how to submit mutations & create new items in our API. To do so, we'll create a form with an input that will create new items in our API & display them to the screen.

现在,我们知道了如何查询数据,让我们看一下如何在我们的API中提交变异和创建新项目。 为此,我们将创建一个带有输入的表单,该表单将在我们的API中创建新项目并将其显示在屏幕上。

To do so, we'll need to do 5 things:

为此,我们需要做5件事:

  1. Import mutation definition

    导入突变定义
  2. Create initial state to hold user input values for the restaurant name & description form data

    创建初始状态以保存餐厅名称和描述表单数据的用户输入值
  3. Create a method for handling the user input into the form

    创建用于处理用户输入到表单的方法
  4. Create a method to call the API & create the mutation

    创建一个调用API的方法并创建变异
  5. Create a form to handle the methods

    创建一个表单来处理方法

First, we'll import the mutation:

首先,我们将导入突变:

import { createRestaurant } from './graphql/mutations'

Next, we'll update the state to hold the restaurant name & description:

接下来,我们将更新状态以保留餐厅名称和描述:

state = { name : '' , description : '' , restaurants : [ ] }

Now, we'll create the two methods we'll need to handle user input & call the API to create a restaurant:

现在,我们将创建处理用户输入所需的两个方法,并调用API创建餐厅:

onChange = e => {
  this . setState ( { [ e . target . name ] : e . target . value } )
}
createRestaurant = async ( ) => {
  const { name , description } = this . state
  if ( name === '' || description === '' ) return
  try {
    const restaurant = { name , description }
    const restaurants = [ ... this . state . restaurants , restaurant ]
    this . setState ( { restaurants , name : '' , description : '' } )
    await API . graphql ( graphqlOperation ( createRestaurant , { input : restaurant } ) )
    console . log ( 'restaurant successfully created!' )
  } catch ( err ) {
    console . log ( 'error: ' , err )
  }
}

In the createRestaurant method we do 5 things:

createRestaurant方法中,我们做五件事:

  1. We first check to make sure the form input values are not empty.

    我们首先检查以确保表单输入值不为空。
  2. We then create a new object called restaurant & store the name & description values in the object.

    然后,我们创建一个名为restaurant的新对象,并将名称和描述值存储在该对象中。
  3. Next, we create a new array called restaurants & set the value as a new array containing all previous restaurants in the state as well as the new restaurant object.

    接下来,我们创建一个名为restaurant的新数组,并将值设置为一个新数组,其中包含该州所有以前的餐厅以及新的restaurant对象。
  4. We call setState to update the UI with the new restaurants array & reset the form fields.

    我们调用setState以使用新的restaurant数组更新UI并重置表单字段。
  5. Finally, we make the API call, passing in the restaurant variable to the API.graphql graphqlOperation as a variable.

    最后,我们进行API调用,将restaurant变量作为变量传递给API.graphql graphqlOperation。

Finally, we'll create the UI for the form fields & button to call the createRestaurant method:

最后,我们将为表单字段和按钮创建UI,以调用createRestaurant方法:

< div style = { styles . inputContainer } >
  < input
    name = 'name'
    placeholder = 'restaurant name'
    onChange = { this . onChange }
    value = { this . state . name }
    style = { styles . input }
  / >
  < input
    name = 'description'
    placeholder = 'restaurant description'
    onChange = { this . onChange }
    value = { this . state . description }
    style = { styles . input }
  / >
< / div >
< button
  style = { styles . button }
  onClick = { this . createRestaurant }
> Create Restaurant < / button >

const styles = {
  // existing styles omitted
  inputContainer : {
    margin : '0 auto' , display : 'flex' , flexDirection : 'column' , width : 300
  } ,
  button : {
    border : 'none' , backgroundColor : '#ddd' , padding : '10px 30px'
  } ,
  input : {
    fontSize : 18 ,
    border : 'none' ,
    margin : 10 ,
    height : 35 ,
    backgroundColor : "#ddd" ,
    padding : 8
  }
}

For a final gist for all of the code for this component, click here.

有关该组件所有代码的最终要点,请单击此处

Now, we should be able to run the app and create new restaurants from the React application:

现在,我们应该能够运行该应用程序并通过React应用程序创建新餐厅:

GraphQL订阅 ( GraphQL Subscriptions )

As I mentioned in the introduction, one of the most powerful features of GraphQL are real-time data with subscriptions.

正如我在简介中提到的那样,GraphQL的最强大功能之一是带有订阅的实时数据。

Subscriptions push data from the server to the clients that choose to listen to the real time data coming from the server. We can subscribe to the creation of a new item, in our case the creation of a new restaurant, & get notified of the creation of the item as well as receive the item data in the subscription callback.

订阅将数据从服务器推送到选择侦听来自服务器的实时数据的客户端。 我们可以订阅新商品的创建,在本例中为新餐厅的创建,并获得商品创建的通知,并在订阅回调中接收商品数据。

To implement subscriptions, we need to do three things:

要实现订阅,我们需要做三件事:

  1. Import the subscription definition

    导入订阅定义
  2. Initialize the subscription in componentDidMount

    componentDidMount初始化订阅
  3. Remove the subscription in componentDidUnmount

    componentDidUnmount删除订阅
// import the subscription defition
import { onCreateRestaurant } from './graphql/subscriptions'

// initialize the subscription in componentDidMount
async componentDidMount ( ) {
  // other code from this method omitted
  this . subscription = API . graphql (
    graphqlOperation ( onCreateRestaurant )
  ) . subscribe ( {
    next : restaurantData => {
      const restaurant = restaurantData . value . data . onCreateRestaurant
      const restaurants = [
        ... this . state . restaurants . filter ( r => {
          return (
            r . name !== restaurant . name && r . description !== restaurant . description
          )
        } ) ,
        restaurant
      ]
      this . setState ( { restaurants } )
    }
  } )
}

// remove the subscription in componentWillUnmount
componentWillUnmount ( ) {
  this . subscription . unsubscribe ( )
}

When the subscription fires, we do 3 things:

当订阅触发时,我们会做三件事:

  1. We create a variable to store the restaurant data coming through the subscription.

    我们创建一个变量来存储通过订阅获得的餐厅数据。
  2. We create a newly updated restaurants array, filtering to make sure there are no duplicate items in case our application is the app creating the mutation. (This implementation checks for duplicate name & descriptions. Ideally, you would have a client ID in which to filter on also stored in the database which would serve as a proper way to filter duplicate items).

    我们创建了一个新近更新的餐厅数组,进行过滤以确保没有重复的项目,以防万一我们的应用程序是创建突变的应用程序。 (此实现检查是否有重复的名称和描述。理想情况下,您将有一个要在其中进行过滤的客户端ID,该ID也会存储在数据库中,这将是过滤重复项的正确方法)。
  3. After the restaurants array is created we reset the state with the new restaurants array.

    在创建餐厅阵列后,我们使用新的餐厅阵列重置状态。

结论 ( Conclusion )

In this tutorial we've walked through all of the typical GraphQL operations you would use in a real-world application. We've also built & deployed a real-world GraphQL API that will automatically scale for you as your application scales.

在本教程中,我们介绍了您将在实际应用程序中使用的所有典型GraphQL操作。 我们还构建并部署了一个实际的GraphQL API,该API将在您的应用程序扩展时自动为您扩展。

The only data source we've looked at so far is DynamoDB, but AWS AppSync also supports other data sources out of the box (including Amazon ElasticSearch, AWS Lambda, & http resolvers). If you're interested in learning more about using other data sources, check out the documentation here.

到目前为止,我们研究过的唯一数据源是DynamoDB,但AWS AppSync还支持其他现成的数据源(包括Amazon ElasticSearch,AWS Lambda和http解析器)。 如果您想了解更多有关使用其他数据源的信息,请参阅此处的文档。

AWS AppSync has 2 JavaScript clients: AWS Amplify (which we have already covered), & the AWS AppSync JavaScript SDK (which we did not cover).

AWS AppSync有2个JavaScript客户端:AWS Amplify(我们已经介绍过)和AWS AppSync JavaScript SDK (我们没有介绍过)。

If you are looking for a solution that handles offline data & operations for you, then take a look at the AWS AppSync JavaScript SDK because it's built in & works out of the box. You can still use Amplify to create & configure the AWS AppSync service while using the AWS AppSync JS SDK to interact with the service.

如果您正在寻找可为您处理离线数据和操作的解决方案,请查看AWS AppSync JavaScript SDK,因为它是内置的并且可以直接使用。 在使用AWS AppSync JS SDK与服务交互时,您仍然可以使用Amplify创建和配置AWS AppSync服务。

翻译自: https://scotch.io/tutorials/graphql-api-with-aws-and-use-with-react

aws api

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值