graphql 客户端_2020年的6个GraphQL顶级客户

这篇博客翻译自https://blog.bitsrc.io/6-top-graphql-clients-for-2020-259e8034ba42,主要介绍了2020年最优秀的六个GraphQL客户端工具。
摘要由CSDN通过智能技术生成

graphql 客户端

We’ll be looking at some of the top GraphQL clients for 2020. Before getting started, it is essential that you have a basic understanding of GraphQL and its server-side and client-side applications.

我们将研究2020年的一些顶级GraphQL客户端。在开始之前,对GraphQL及其服务器端和客户端应用程序有基本的了解是至关重要的。

什么是GraphQL? (What is GraphQL?)

If GraphQL seems somewhat familiar, it’s because it sounds like the names of other types of Query Languages like MySQL. While GraphQL is a Query Language (QL), it works differently to a typical QL. It uses a single API endpoint to allow applications to query for exactly the data they want through an HTTP Post request. This is a significant improvement from having to call upon a specific endpoint for each data type.

如果GraphQL看起来有些熟悉,那是因为它听起来像MySQL等其他类型的查询语言的名称。 尽管GraphQL是一种查询语言(QL),但它的工作方式不同于典型的QL。 它使用单个API端点,以允许应用程序通过HTTP Post请求精确查询所需的数据。 与必须为每种数据类型调用特定终结点相比,这是一个重大改进。

This technology is relatively new and was released to the public by Facebook in 2015. However, it was part of Facebook since 2012 and has seen rapid growth and acceptance since. It is a powerful Query Language that can be used to communicate between a client (usually a browser-based application) and a server. It enables structuring data-driven applications more efficiently compared to a RESTful approach.

该技术是相对较新的技术,于2015年由Facebook公开发布。但是,自2012年以来,它已成为Facebook的一部分,自此以来Swift增长并被接受。 它是一种功能强大的查询语言,可用于在客户端(通常是基于浏览器的应用程序)和服务器之间进行通信。 与RESTful方法相比,它可以更有效地构建数据驱动的应用程序。

GraphQL can be implemented in any server-side language and frontend language framework. It is essential to keep in mind that GraphQL is not bound to any particular database technology or application.

GraphQL可以用任何服务器端语言和前端语言框架来实现。 必须记住,GraphQL不受任何特定数据库技术或应用程序的约束。

GraphQL的优势 (The Advantages of GraphQL)

  • In comparison to RESTful web services, it is possible to request specific data points without receiving the entire data object. The required data points can be specified in the GraphQL query (HTTP Post request).

    与RESTful Web服务相比,可以在不接收整个数据对象的情况下请求特定的数据点。 可以在GraphQL查询(HTTP Post请求)中指定所需的数据点。
  • GraphQL is strongly typed, and strict document requirements make the available data points transparent to client applications.

    GraphQL是强类型的,并且严格的文档要求使可用的数据点对客户端应用程序透明。
  • One disadvantage of RESTful endpoints is that they require a lot of maintenance if your organization’s data structure changes frequently. GraphQL is flexible and allows adapting to these changes rapidly as the changes only need to be handled in the GraphQL queries.

    RESTful终结点的一个缺点是,如果组织的数据结构频繁更改,则它们需要大量维护。 GraphQL具有灵活性,并允许快速适应这些更改,因为这些更改仅需要在GraphQL查询中进行处理。

GraphQL的缺点 (The Disadvantages of GraphQL)

While GraphQL has many advantages, it also brings along some fundamental issues that can be deal-breakers.

尽管GraphQL具有许多优点,但它也带来了一些可能破坏交易的基本问题。

  • Unlike RESTful endpoints, GraphQL’s single endpoint does not have native caching capabilities. You will need to set up your own caching logic.

    与RESTful终结点不同,GraphQL的单个终结点不具有本地缓存​​功能。 您将需要设置自己的缓存逻辑。
  • Another issue is that all requests return an HTTP 200 response, irrespective of the response’s actual status.

    另一个问题是,无论响应的实际状态如何,所有请求都将返回HTTP 200响应。
  • Setting up a GraphQL endpoint can be relatively more complicated than a RESTful web service. If your data structures are relatively simple and don’t require constant changes, it may be worthwhile to avoid GraphQL.

    设置GraphQL端点可能比RESTful Web服务相对复杂。 如果您的数据结构相对简单并且不需要不断更改,则避免GraphQL是值得的。

As you now know the pros and cons of GraphQL, let’s see the best GraphQL clients for 2020.

现在您知道了GraphQL的优缺点,让我们来看看2020年最好的GraphQL客户。

Tip: Use Bit (Github) to share, document, and manage reusable React components. It’s a great way to increase code reuse, speed up development, and build apps that scale.

提示:使用Bit ( Github )共享,记录和管理可重用的React组件。 这是增加代码重用,加速开发并构建可扩展应用程序的好方法。

Image for post
Example: exploring shared React components on Bit.dev
示例:在 Bit.dev上浏览共享的React组件

1.阿波罗客户 (1. Apollo-Client)

Apollo-Client is a comprehensive JavaScript library used for managing local and remote data with GraphQL. It has many benefits like state management, fetching, caching, and modifying application data. It provides an efficient and declarative way to structure code in line with modern development processes. Apollo-Client has native support for React and extends to other view layers like Vue and Ember through community projects.

Apollo-Client是一个全面JavaScript库,用于通过GraphQL管理本地和远程数据。 它具有许多优点,例如状态管理,获取,缓存和修改应用程序数据。 它提供了一种有效的声明式方式来根据现代开发流程来构造代码。 Apollo-Client对React具有原生支持,并通过社区项目扩展到其他视图层,例如Vue和Ember。

The latest version of Apollo supports garbage collection, storage for both normalized and non-normalized data. Also, it has customization of cached data with TypePolicy and FieldPolicy APIs.

最新版本的Apollo支持垃圾收集,标准化数据和非标准化数据的存储。 此外,它还使用TypePolicy和FieldPolicy API自定义缓存数据。

在React应用程序中使用Apollo-Client的示例代码 (Sample code for using Apollo-Client in a React application)

Let’s install the latest version of Apollo client and its required packages:

让我们安装最新版本的Apollo客户端及其必需的软件包:

npm install @apollo/client graphql

npm install @apollo/client graphql

Now create a component named apolloClient.js. Once all dependencies have been installed, initialize an ApolloClient instance. Start by importing ApolloClient and InMemoryCache.

现在创建一个名为apolloClient.js的组件。 安装所有依赖项后,初始化ApolloClient实例。 首先导入ApolloClient和InMemoryCache。

import { ApolloClient, InMemoryCache, gql } from “@apollo/client”;

import { ApolloClient, InMemoryCache, gql } from “@apollo/client”;

Now define an export function as follows and add the following code snippets inside it:

现在,按如下所示定义导出函数,并在其中添加以下代码段:

As you may have already noticed, the URI is a URL of a GraphQL server running within a CodeSandbox. Now the client is ready to fetch the data.

您可能已经注意到,URI是在CodeSandbox中运行的GraphQL服务器的URL。 现在,客户端已准备好获取数据。

Define a query string as shown below. It is recommended to import the gql function to parse the query string (already imported).

定义查询字符串,如下所示。 建议导入gql函数以解析查询字符串(已导入)。

Open the ApolloClient.js component and import the ApolloProvider as follows to connect it to the React component.

打开ApolloClient.js组件并按如下所示导入ApolloProvider,以将其连接到React组件。

import { ApolloProvider } from “@apollo/client”;

import { ApolloProvider } from “@apollo/client”;

Add the following code snippet into the return statement as follows:

将以下代码段添加到return语句中,如下所示:

Now import the ApolloClientExample into the App.js component as follows:

现在,如下所示将ApolloClientExample导入App.js组件:

import { ApolloClientExapmle } from “./graphql/apolloClient”;

import { ApolloClientExapmle } from “./graphql/apolloClient”;

Add the following return statement:

添加以下返回语句:

That’s it. Let’s run the code and inspect the response in the console. As evident in the screenshot below, you will be able to observe a data property with rates attached, along with loading and networkStatus.

而已。 让我们运行代码并在控制台中检查响应。 从下面的屏幕截图中可以明显看出,您将能够观察到数据属性以及附加的rate以及load和networkStatus

Image for post

GraphQL-请求 (GraphQL-Request)

GraphQL-Request is known as Isomorphic because it works with both Node and browsers. It is a minimal GraphQL client supporting Node and browsers for scripts and simple applications and includes several features. GraphQL-Request is a lightweight and simple GraphQL client that supports async and await. More importantly, it supports Typescript.

GraphQL-Request被称为同构的,因为它可与Node和浏览器一起使用。 它是一个最小的GraphQL客户端,它支持Node和用于脚本和简单应用程序的浏览器,并包括多个功能。 GraphQL-Request是支持异步和等待的轻量级简单GraphQL客户端。 更重要的是,它支持Typescript。

在React应用程序中使用GraphQL-Request的示例代码 (Sample code for using GraphQL-Request in a React application)

Let’s create a simple GraphQL query. Start by installing the latest version of graphql-request using node package manager (npm):

让我们创建一个简单的GraphQL查询。 首先使用节点包管理器(npm)安装最新版本的graphql-request:

npm install graphql-request

npm install graphql-request

Now create a file named graphqlRequest.js and import the graphql-request as follows:

现在创建一个名为graphqlRequest.js的文件,并按如下所示导入graphql-request:

import request from “graphql-request”;

import request from “graphql-request”;

Inside the newly created file, add an export function with the following query to retrieve the data of a movie:

在新创建的文件中,使用以下查询添加导出功能以检索电影的数据:

Log the response in the console with the following code so that we can inspect it:

使用以下代码在控制台中记录响应,以便我们对其进行检查:

Add the following return statement to complete the component.

添加以下return语句以完成组件。

Import the graphqlRequest.js component into the App.js component and call it as follows:

将graphqlRequest.js组件导入App.js组件,并按以下方式调用它:

Now run the application and inspect the console to view the data of the movie in the response object.

现在运行该应用程序,并检查控制台以查看响应对象中电影的数据。

Image for post

图QL-CLI (GraphQL-CLI)

GraphQL-CLI is a bit different from the clients we looked at up to now. It is command-line based and provides many useful tools for creating and managing applications that use GraphQL. In addition to the many commands it provides to make your routine tasks more efficient, you will be able to extend custom commands through plugins. GraphQL-CLI’s vivid eco-system opens up to many resources like libraries, editors, and IDEs.

GraphQL-CLI与我们到目前为止研究的客户端有些不同。 它基于命令行,并提供许多有用的工具来创建和管理使用GraphQL的应用程序。 除了提供许多使您的例行任务更有效率的命令外,您还可以通过插件扩展自定义命令。 GraphQL-CLI生动的生态系统向许多资源开放,例如库,编辑器和IDE。

An interesting fact about GraphQL-CLI is that it enables you to create a functioning full-stack app structure within minutes using the init command, as shown below.

关于GraphQL-CLI的一个有趣的事实是,它使您可以使用init命令在几分钟之内创建一个正常运行的全栈应用程序结构,如下所示。

在React应用程序中使用GraphQL-CLI的示例代码 (Sample code for using GraphQL-CLI in a React application)

Install the CLI through npm using the command line interface (CMD).

使用命令行界面(CMD)通过npm安装CLI。

npm install graphql-cli@canary

npm install graphql-cli@canary

Let’s create a new project with GraphQL-CLI through the init command.

让我们通过init命令使用GraphQL-CLI创建一个新项目。

graphql init

graphql init

Follow the process by answering the questions as follows. This is to suit our example code. You can also try out many other scenarios.

通过回答以下问题来遵循该过程。 这适合我们的示例代码。 您还可以尝试许多其他方案。

Image for post

Change the directory to the project folder:

将目录更改为项目文件夹:

cd Full Stack

cd Full Stack

Now install the relevant dependencies:

现在安装相关的依赖项:

yarn install

yarn install

Change the directory to the project folder i.e. GraphQL-Project and perform the following actions:

将目录更改为项目文件夹,即GraphQL-Project,然后执行以下操作:

Start the database

启动数据库

docker-compose up -d

docker-compose up -d

Generate resources (schema and resolvers) and create the database

生成资源(模式和解析器)并创建数据库

yarn graphql generate — backendyarn graphql generate -backendyarn graphql generate — db

yarn graphql generate — backend yarn graphql generate -backend yarn graphql generate — db

Generate types for Database Schema and Resolvers

生成数据库模式和解析器的类型

yarn schemats generateyarn graphql codegen

yarn schemats generate yarn graphql codegen yarn schemats generate

Start the server

启动服务器

yarn start: server

yarn start: server

Generate queries, mutations, and subscriptions for the client-side project

生成客户端项目的查询,变异和订阅

yarn graphql generate — client

yarn graphql generate — client

Generate React components

生成React组件

yarn graphql codegen

yarn graphql codegen

Start React App

启动React App

yarn start:client

yarn start:client

Here is the output that you will see.

这是您将看到的输出。

Image for post

GraphQL-撰写 (GraphQL-Compose)

GraphQL-Compose is an excellent toolkit for generating complex GraphQL schemas on Node.js. It is possibly the best tool to build a GraphQL schema generator and includes methods for editing GraphQL output/input types. A graphql fieldConfigs has been introduced that is a Resolver that can be used for searching, updating, and deleting records.

GraphQL-Compose是一个出色的工具包,用于在Node.js上生成复杂的GraphQL模式。 它可能是构建GraphQL模式生成器的最佳工具,并且包括用于编辑GraphQL输出/输入类型的方法。 引入了graphql fieldConfigs,它是可用于搜索,更新和删除记录的解析器。

GraphQL-Compose provides a method for OutputType to InputType conversion and a projection parser from AST. This client provides a type registry with a bunch of methods for programmatic schema construction.

GraphQL-Compose提供了将OutputType转换为InputType的方法以及AST的投影解析器。 该客户端为类型注册表提供了一系列用于编程模式构造的方法。

The GraphQL schema language can be used to define:

GraphQL模式语言可用于定义:

Type generators built on top:

建立在顶部的类型生成器:

  • GraphQL-Compose-JSON

    GraphQL-Compose-JSON
  • GraphQL-Compose-Mongoose

    GraphQL-组合猫鼬
  • GraphQL-Compose-ElasticSearch

    GraphQL-Compose-ElasticSearch
  • GraphQL-Compose-AWS

    GraphQL-Compose-AWS

Utility Plugins:

实用程序插件:

  • GraphQL-Compose-Relay

    GraphQL-复合继电器
  • GraphQL-Compose-Connection

    GraphQL-Compose-Connection
  • GraphQL-Compose-DataLoader

    GraphQL-Compose-DataLoader

在React应用程序中使用GraphQL-Compose的示例代码 (Sample code for using GraphQL-Compose in a React application)

Install it via npm as follows:

通过npm进行安装,如下所示:

npm install graphql-compose

npm install graphql-compose

Now import the required modules:

现在导入所需的模块:

import { schemaComposer } from “graphql-compose”;

import { schemaComposer } from “graphql-compose”;

Let’s create some mock data — two arrays for authors and posts.

让我们创建一些模拟数据-作者和帖子的两个数组。

Building a GraphQL schema begins with complex type declarations. They must be named uniquely. Let’s create two distinct types as follows:

构建GraphQL模式始于复杂的类型声明。 它们必须是唯一的。 让我们创建两个不同的类型,如下所示:

Now create a relation between them:

现在在它们之间创建一个关系:

Now let’s build a schema. We have just established two types, and they are linked and able to fetch data. Now it is recommended to initialize the schema using schemaComposer, which is imported from the module imported above.

现在让我们构建一个模式。 我们刚刚建立了两种类型,它们是链接的并且能够获取数据。 现在,建议使用从上面导入的模块中导入的schemaComposer初始化架构。

Specify the data that is required in the query:

指定查询中所需的数据:

Requests which modify data need to be put into Mutation.

修改数据的请求需要放入Mutation中。

We are now ready to build a schema which must be passed to express-graphql:

现在,我们准备构建必须传递给express-graphql的模式:

export const schema = schemaComposer.buildSchema();

export const schema = schemaComposer.buildSchema();

Now let’s create an HTTP server. We have constructed the schema successfully; it needs to implement a server. As mentioned above let’s import express-graphql and its required dependencies:

现在让我们创建一个HTTP服务器。 我们已经成功构建了模式; 它需要实现一个服务器。 如上所述,让我们导入express-graphql及其必需的依赖项:

That’s it. We have developed an application using GraphQL-Compose.

而已。 我们使用GraphQL-Compose开发了一个应用程序。

@ octokit / GraphQL (@octokit/GraphQL)

This is a GitHub GraphQL API client for browsers and Node. It provides several advantages, such as:

这是用于浏览器和Node的GitHub GraphQL API客户端。 它具有几个优点,例如:

  • Sending simple queries

    发送简单查询
  • Manage authentication

    管理身份验证
  • Supports headers and variables

    支持标题和变量
  • Utilizes custom @octokit/request instances

    利用自定义@ octokit / request实例

Octokit.GraphQL allows .Net applications to access the GitHub GraphQL API by exposing it as a strongly typed Language Integrated Query that strictly adheres to the GraphQL query syntax. Another important benefit of this library is that it allows developers to write tests with mock data to test their applications.

Octokit.GraphQL通过将.Net应用程序公开为严格遵守GraphQL查询语法的强类型语言集成查询,从而允许.Net应用程序访问GitHub GraphQL API。 该库的另一个重要优点是,它允许开发人员使用模拟数据编写测试以测试其应用程序。

在React应用程序中使用Octokit.GraphQL的示例代码 (Sample code for using Octokit.GraphQL in a React application)

Install via npm as follows:

通过npm安装,如下所示:

npm install @octokit/graphql

npm install @octokit/graphql

Now import graphql from octokit:

现在从octokit导入graphql:

import { graphql } from “@octokit/graphql”;

import { graphql } from “@octokit/graphql”;

Send a simple query with the following code:

使用以下代码发送一个简单的查询:

It is recommended that these requests are authorized through an authorization header. A PAT (Personal Access Token) can be obtained and used as the key in the authorization header as shown above.

建议通过授权标头对这些请求进行授权。 可以获取PAT(个人访问令牌)并将其用作授权标头中的密钥,如上所示。

A PAT can be generated via https://github.com/settings/tokens

可以通过https://github.com/settings/tokens生成PAT

中继 (Relay)

Relay is another important GraphQL client that is specifically built for React applications. Its design focuses mainly on user-friendliness, extensibility, and performance. In addition to the usual bells and whistles available with most GraphQL clients, Relay enhances the encapsulation already available among React components.

Relay是另一个重要的GraphQL客户端,专门为React应用程序而构建。 它的设计主要集中在用户友好性,可扩展性和性能上。 除了大多数GraphQL客户端可用的常规功能外,Relay还增强了React组件之间已经可用的封装。

At least a basic understanding of data binding within React is required to fully understand Relay. Relay is easily configured with a single config file through the relay-config package.

至少需要对React内的数据绑定有基本的了解,才能完全了解Relay。 通过relay-config软件包,可以使用单个配置文件轻松配置Relay。

在React应用程序中使用Relay的示例代码 (Sample code for using Relay in a React application)

Start by installing the react-relay package via npm:

首先通过npm安装react-relay软件包:

npm install react-relay

npm install react-relay

Now create a component named ReactRelay.js and set up the relay environment. The environment bundles together the configuration, cache storage, and network-handling that Relay needs in order to operate.

现在创建一个名为ReactRelay.js的组件并设置中继环境。 该环境将中继运行所需的配置,缓存存储和网络处理捆绑在一起。

Install the module required to configure the environment:

安装配置环境所需的模块:

npm install relay-runtime

npm install relay-runtime

The next step is to import the relay-time module as follows:

下一步是如下导入中继时间模块:

import { Environment, Network, RecordSource, Store } from “relay-runtime”;

This is the code for the fetch function:

这是获取功能的代码:

Render the query as follows:

呈现查询如下:

Add the following configurations:

添加以下配置:

Now create an export function as ReactRelay as follows:

现在创建一个导出函数作为ReactRelay,如下所示:

export const Example = () => {}

export const Example = () => {}

Add the following code snippet into the above-mentioned return statement.

将以下代码段添加到上述return语句中。

Open the App.js file and import the ReactRelay as follows:

打开App.js文件并按如下所示导入ReactRelay:

That’s all there is to this simple example. But there is a lot more that you can do with React Relay.

这就是这个简单示例的全部内容。 但是,使用React Relay还可以做很多事情。

结论 (Conclusion)

To fully understand GraphQL and its benefits, you need to know the pros and cons of RESTful web services. GraphQL is an excellent alternative, but there are some scenarios in which it is not suitable. We looked at them at the beginning of this article.

要完全了解GraphQL及其好处,您需要了解RESTful Web服务的优缺点。 GraphQL是一个很好的替代方案,但是在某些情况下它不合适。 我们在本文开头介绍了它们。

Once you have identified that GraphQL can add value to your applications, the next step is to identify a GraphQL client that suits the programming language and framework you use, and more importantly, your business requirements.

一旦确定GraphQL可以为您的应用程序增加价值,下一步就是确定一个GraphQL客户端,该客户端适合您使用的编程语言和框架,更重要的是您的业务需求。

学到更多 (Learn More)

翻译自: https://blog.bitsrc.io/6-top-graphql-clients-for-2020-259e8034ba42

graphql 客户端

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值