apollo调试工具_GraphQL工具包Apollo的完整介绍

apollo调试工具

Interested in learning JavaScript? Get my ebook at jshandbook.com

有兴趣学习JavaScript吗? 在jshandbook.com上获取我的电子书

阿波罗简介 (Introduction to Apollo)

In the last few years, GraphQL has gotten hugely popular as an alternative approach to building an API over REST.

在过去的几年中, GraphQL作为在REST上构建API的替代方法而广受欢迎。

GraphQL is a great way to let the client decide which data they want to be transmitted over the network, rather than having the server send a fixed set of data.

GraphQL是让客户端决定要通过网络传输哪些数据的好方法,而不是让服务器发送一组固定的数据。

Also, it allows you to specify nested resources, reducing the back and forth sometimes required when dealing with REST APIs.

此外,它还允许您指定嵌套资源,从而减少了在处理REST API时有时需要来回的问题。

Apollo is a team and community that builds on top of GraphQL, and provides different tools that help you build your projects.

Apollo是一个基于GraphQL的团队和社区,并提供不同的工具来帮助您构建项目。

The tools provided by Apollo are mainly three: Client, Server, Engine.

Apollo提供的工具主要有三种: ClientServerEngine

Apollo Client helps you consume a GraphQL API, with support for the most popular frontend web technologies like React, Vue, Angular, Ember, and Meteor. It also supports native development on iOS and Android.

Apollo Client可帮助您使用GraphQL API,并支持最流行的前端Web技术,例如React,Vue,Angular,Ember和Meteor。 它还支持iOS和Android上的本机开发。

Apollo Server is the server part of GraphQL, which interfaces with your backend and sends responses back to the client requests.

Apollo服务器是GraphQL的服务器部分,它与您的后端连接并将响应发送回客户端请求。

Apollo Engine is a hosted infrastructure (SaaS) that serves as a middle man between the client and your server, providing caching, performance reporting, load measurement, error tracking, schema field usage statistics, historical stats and many more goodies. It’s currently free up to 1 million requests per month, and it’s the only part of Apollo that’s not open source and free. It provides funding for the open source part of the project.

Apollo Engine是一个托管基础结构(SaaS),充当客户端和服务器之间的中间人,提供缓存,性能报告,负载测量,错误跟踪,架构字段使用情况统计信息,历史统计信息以及更多其他功能。 目前,它每月最多免费释放一百万个请求,这是Apollo唯一不开源且免费的部分。 它为项目的开源部分提供资金。

It’s worth noting that those three tools are not linked together in any way, and you can use just Apollo Client to interface with a 3rd part API, or serve an API using Apollo Server without having a client at all, for example.

值得注意的是,这三个工具没有以任何方式链接在一起,例如,您可以仅使用Apollo Client与第三部分API进行接口,也可以使用Apollo Server来提供API,例如根本不需要客户端。

使用Apollo的一些好处 (Some benefits of using Apollo)

It’s all compatible with the GraphQL standard specification, so there is no proprietary or incompatible tech in Apollo.

它们都与GraphQL标准规范兼容 ,因此Apollo中没有专有或不兼容的技术。

But it’s very convenient to have all those tools together under a single roof as a complete suite for all your GraphQL-related needs.

但是将所有这些工具放在一起作为一个完整套件非常方便,可以满足您所有与GraphQL相关的需求。

Apollo strives to be easy to use and easy to contribute to.

阿波罗(Apollo)努力做到易于使用和易于贡献。

Apollo Client and Apollo Server are all community projects, built by the community, for the community. Apollo is backed by the Meteor Development Group (the company behind Meteor), a very popular JavaScript framework.

Apollo Client和Apollo Server都是由社区为社区构建的社区项目。 Apollo得到了非常流行JavaScript框架Meteor Development Group ( Meteor背后的公司)的支持。

Apollo is focused on keeping things simple. This is something key to the success of a technology that wants to become popular. Much of the tech or frameworks or libraries out there might be overkill for 99% of small or medium companies, and is really suited for the big companies with very complex needs.

阿波罗致力于保持简单 。 这是想要普及的技术成功的关键。 那里的许多技术,框架或库对于99%的中小型公司来说可能是过大的杀伤力,并且确实适合具有非常复杂需求的大公司。

阿波罗客户 (Apollo Client)

Apollo Client is the leading JavaScript client for GraphQL. Since it’s community-driven, it’s designed to let you build UI components that interface with GraphQL data — either in displaying that data, or in performing mutations when certain actions happen.

Apollo客户端是GraphQL的领先JavaScript客户端。 由于它是由社区驱动的,因此可以让您构建与GraphQL数据交互的UI组件-在显示数据或执行某些操作时执行突变。

You don’t need to change everything in your application to make use of Apollo Client. You can start with just one tiny layer and one request, and expand from there.

您无需更改应用程序中的任何内容即可使用Apollo Client。 您可以从一个很小的层和一个请求开始,然后从那里扩展。

Most of all, Apollo Client is built to be simple, small, and flexible from the ground up.

最重要的是,Apollo Client的构建从一开始就是简单,小巧和灵活。

In this post I’m going to detail the process of using Apollo Client within a React application.

在这篇文章中,我将详细介绍在React应用程序中使用Apollo Client的过程。

I’ll use the GitHub GraphQL API as a server.

我将使用GitHub GraphQL API作为服务器。

启动一个React应用 (Start a React app)

I use create-react-app to setup the React app, which is very convenient and just adds the bare bones of what we need:

我使用create-react-app设置React应用程序,这非常方便,并且只需添加我们所需的内容即可:

npx create-react-app myapp

npx is a command available in the latest npm versions. Update npm if you do not have this command.

npx 是最新npm版本中可用的命令。 如果没有此命令,请更新npm。

Start the app local server with

使用以下命令启动应用程序本地服务器

yarn start

Open src/index.js:

打开src/index.js

import React from 'react'import ReactDOM from 'react-dom'import './index.css'import App from './App'import registerServiceWorker from './registerServiceWorker'ReactDOM.render(<App />, document.getElementById('root'))registerServiceWorker()

and remove all this content.

并删除所有这些内容。

开始使用Apollo Boost (Get started with Apollo Boost)

Apollo Boost is the easiest way to start using Apollo Client on a new project. We’ll install that in addition to react-apollo and graphql.

Apollo Boost是在新项目上开始使用Apollo Client的最简单方法。 除了react-apollographql之外,我们还将安装它。

In the console, run

在控制台中,运行

yarn add apollo-boost react-apollo graphql

or with npm:

或使用npm:

npm install apollo-boost react-apollo graphql --save

创建一个ApolloClient对象 (Create an ApolloClient object)

You start by importing ApolloClient from apollo-client in index.js:

首先从index.js apollo-client导入ApolloClient:

import { ApolloClient } from 'apollo-client'const client = new ApolloClient()

By default Apollo Client uses the /graphql endpoint on the current host, so let’s use an Apollo Link to specify the details of the connection to the GraphQL server by setting the GraphQL endpoint URI.

默认情况下,Apollo Client在当前主机上使用/graphql端点,因此让我们使用Apollo Link通过设置GraphQL端点URI来指定与GraphQL服务器的连接的详细信息。

An Apollo Link is represented by an HttpLink object, which we import from apollo-link-http.

Apollo链接由HttpLink对象表示,该对象是我们从apollo-link-http导入的。

Apollo Link provides us a way to describe how we want to get the result of a GraphQL operation, and what we want to do with the response.

Apollo Link为我们提供了一种描述我们如何获取GraphQL操作结果以及如何对响应进行处理的方法。

In short, you create multiple Apollo Link instances that all act on a GraphQL request one after another, providing the final result you want. Some Links can give you the option of retrying a request if not successful, batching, and much more.

简而言之,您将创建多个Apollo Link实例,这些实例一个接一个地作用于GraphQL请求,从而提供所需的最终结果。 某些链接可以让您选择重试请求(如果未成功),批处理等等。

We’ll add an Apollo Link to our Apollo Client instance to use the GitHub GraphQL endpoint URI https://api.github.com/graphql

我们将Apollo链接添加到我们的Apollo Client实例,以使用GitHub GraphQL端点URI https://api.github.com/graphql

import { ApolloClient } from 'apollo-client'import { HttpLink } from 'apollo-link-http'const client = new ApolloClient({  link: new HttpLink({ uri: 'https://api.github.com/graphql' })})

快取 (Caching)

We’re not done yet. Before having a working example we must also tell ApolloClient which caching strategy to use: InMemoryCache is the default and it’s a good one with which to start.

我们还没有完成。 在ApolloClient示例之前,我们还必须告诉ApolloClient哪种缓存策略InMemoryCache是默认的,并且是一个很好的起点。

import { ApolloClient } from 'apollo-client'import { HttpLink } from 'apollo-link-http'import { InMemoryCache } from 'apollo-cache-inmemory'const client = new ApolloClient({  link: new HttpLink({ uri: 'https://api.github.com/graphql' }),  cache: new InMemoryCache()})

使用ApolloProvider (Use ApolloProvider)

Now we need to connect the Apollo Client to our component tree. We do so using ApolloProvider, by wrapping our application component in the main React file:

现在,我们需要将Apollo客户端连接到我们的组件树。 我们通过使用ApolloProvider来实现此ApolloProvider ,方法是将应用程序组件包装在主React文件中:

import React from 'react'import ReactDOM from 'react-dom'import { ApolloClient } from 'apollo-client'import { HttpLink } from 'apollo-link-http'import { InMemoryCache } from 'apollo-cache-inmemory'import { ApolloProvider } from 'react-apollo'import App from './App'const client = new ApolloClient({  link: new HttpLink({ uri: 'https://api.github.com/graphql' }),  cache: new InMemoryCache()})ReactDOM.render(  <ApolloProvider client={client}>    <App />  </ApolloProvider>,  document.getElementById('root'))

This is enough to render the default create-react-app screen, with Apollo Client initialized:

这足以渲染默认的create-react-app屏幕,并初始化Apollo Client:

gql模板标签 (The gql template tag)

We’re now ready to do something with Apollo Client, and we’re going to fetch some data from the GitHub API and render it.

现在,我们准备使用Apollo Client做一些事情,并且我们将从GitHub API中获取一些数据并进行渲染。

To do so, we need to import the gql template tag:

为此,我们需要导入gql模板标签:

import gql from 'graphql-tag'

Any GraphQL query will be built using this template tag, like this:

任何GraphQL查询都将使用此模板标记构建,如下所示:

const query = gql`  query {    ...  }`

执行GraphQL请求 (Perform a GraphQL request)

gql was the last item we needed in our toolset.

gql是我们工具集中需要的最后一项。

We’re now ready to do something with Apollo Client, and we’re going to fetch some data from the GitHub API and render it.

现在,我们准备使用Apollo Client做一些事情,并且我们将从GitHub API中获取一些数据并进行渲染。

获取API的访问令牌 (Obtain an access token for the API)

The first thing to do is to obtain a personal access token from GitHub.

首先要做的是从GitHub 获取个人访问令牌

GitHub makes it easy by providing an interface from which you select any permission you might need:

GitHub提供了一个界面,您可以从中选择可能需要的任何权限,从而使其变得容易:

For the sake of this example tutorial, you don’t need any of those permissions. They are meant for access to private user data, but we will just query the public repositories data.

在本示例教程中,您不需要任何这些权限。 它们旨在访问私有用户数据,但我们仅查询公共存储库数据。

The token you get is an OAuth 2.0 Bearer token.

您获得的令牌是OAuth 2.0承载令牌

You can easily test it by running from the command line:

您可以通过从命令行运行轻松地对其进行测试:

$ curl -H "Authorization: bearer ***_YOUR_TOKEN_HERE_***" -X POST -d " \ { \   \"query\": \"query { viewer { login }}\" \ } \" https://api.github.com/graphql

which should give you the result

这应该给你结果

{"data":{"viewer":{"login":"***_YOUR_LOGIN_NAME_***"}}}

or

要么

{  "message": "Bad credentials",  "documentation_url": "https://developer.github.com/v4"}

if something went wrong.

如果出现问题。

So, we need to send the Authorization header along with our GraphQL request, just like we did in the curl request above.

因此,我们需要将Authorization标头与GraphQL请求一起发送,就像我们在上面的curl请求中所做的一样。

We can do this with Apollo Client by creating an Apollo Link middleware. Start with installing apollo-link-context:

我们可以通过创建Apollo Link中间件来使用Apollo Client来实现。 从安装apollo-link-context

npm install apollo-link-context

This package allows us to add an authentication mechanism by setting the context of our requests.

该软件包允许我们通过设置请求的上下文来添加身份验证机制。

We can use it in this code by referencing the setContext function in this way:

通过以这种方式引用setContext函数,可以在此代码中使用它:

const authLink = setContext((_, { headers }) => {  const token = '***YOUR_TOKEN**'  return {    headers: {      ...headers,      authorization: `Bearer ${token}`    }  }})

and once we have this new Apollo Link, we can compose it with the HttpLink we already had by using the concat() method on a link:

一旦有了这个新的Apollo链接,就可以通过在链接上使用concat()方法将其与已经拥有的HttpLink 组合起来:

const link = authLink.concat(httpLink)

Here is the full code for the src/index.js file with the code we have right now:

这是src/index.js文件的完整代码,其中包含我们现在拥有的代码:

import React from 'react'import ReactDOM from 'react-dom'import { ApolloClient } from 'apollo-client'import { HttpLink } from 'apollo-link-http'import { InMemoryCache } from 'apollo-cache-inmemory'import { ApolloProvider } from 'react-apollo'import { setContext } from 'apollo-link-context'import gql from 'graphql-tag'import App from './App'const httpLink = new HttpLink({ uri: 'https://api.github.com/graphql' })const authLink = setContext((_, { headers }) => {  const token = '***YOUR_TOKEN**'  return {    headers: {      ...headers,      authorization: `Bearer ${token}`    }  }})const link = authLink.concat(httpLink)const client = new ApolloClient({  link: link,  cache: new InMemoryCache()})ReactDOM.render(  <ApolloProvider client={client}>    <App />  </ApolloProvider>,  document.getElementById('root'))

WARNING ⚠️ ? Keep in mind that this code is an example for educational purposes. It exposes your GitHub GraphQL API for the world to see in your frontend-facing code. Production code needs to keep this token private.

警告⚠️? 请记住,此代码只是出于教育目的的示例 它向全世界公开了您的GitHub GraphQL API,供您在面向前端的代码中查看。 生产代码需要将此令牌设为私有。

We can now make the first GraphQL request at the bottom of this file, and this sample query asks for the names and the owners of the 10 most popular repositories with more than 50k stars:

现在,我们可以在该文件的底部发出第一个GraphQL请求,此示例查询将询问10个最受欢迎的,存储量超过5万颗星的存储库的名称和所有者:

const POPULAR_REPOSITORIES_LIST = gql`{  search(query: "stars:>50000", type: REPOSITORY, first: 10) {    repositoryCount    edges {      node {        ... on Repository {          name          owner {            login          }          stargazers {            totalCount          }        }      }    }  }}`client.query({ query: POPULAR_REPOSITORIES_LIST }).then(console.log)

Running this code successfully returns the result of our query in the browser console:

运行此代码成功返回浏览器控制台中查询的结果:

呈现组件中的GraphQL查询结果集 (Render a GraphQL query result set in a component)

What we’ve seen up to now is already cool. What’s even cooler is using the GraphQL result set to render your components.

到目前为止,我们已经看到的很酷。 更酷的是使用GraphQL结果集渲染组件。

We let Apollo Client have the burden (or joy) or fetching the data and handling all the low-level stuff. This lets us focus on showing the data by using the graphql component enhancer offered by react-apollo:

我们让Apollo Client承担(或享受)负担,或者获取数据并处理所有低层次的东西。 这让我们专注于通过使用react-apollo提供的graphql组件增强器来显示数据:

import React from 'react'import { graphql } from 'react-apollo'import { gql } from 'apollo-boost'const POPULAR_REPOSITORIES_LIST = gql`{  search(query: "stars:>50000", type: REPOSITORY, first: 10) {    repositoryCount    edges {      node {        ... on Repository {          name          owner {            login          }          stargazers {            totalCount          }        }      }    }  }}`const App = graphql(POPULAR_REPOSITORIES_LIST)(props =>  <ul>    {props.data.loading ? '' : props.data.search.edges.map((row, i) =>      <li key={row.node.owner.login + '-' + row.node.name}>        {row.node.owner.login} / {row.node.name}: {' '}        <strong>          {row.node.stargazers.totalCount}        </strong>      </li&gt;    )}  </ul>)export default App

Here is the result of our query rendered in the component ?

这是在组件中呈现查询结果的结果吗?

阿波罗服务器 (Apollo Server)

A GraphQL server has the job of accepting incoming requests on an endpoint, interpreting the request and looking up any data that’s necessary to fulfill the client’s needs.

GraphQL服务器的工作是在终结点计算机上接受传入的请求,解释请求并查找满足客户端需求所需的任何数据。

There are tons of different GraphQL server implementations for every possible language.

每种可能的语言都有许多不同的GraphQL服务器实现。

Apollo Server is a GraphQL server implementation for JavaScript, in particular for the Node.js platform.

Apollo Server是GraphQL服务器实现,用于JavaScript,尤其是Node.js平台

It supports many popular Node.js frameworks, including:

它支持许多流行的Node.js框架,包括:

The Apollo Server basically gives us three things:

Apollo服务器基本上为我们提供了三件事:

  • A way to describe our data with a schema.

    模式描述我们的数据的一种方法。

  • The framework for resolvers, which are functions we write to fetch the data needed to fulfill a request.

    解析程序的框架,我们编写的函数用于获取满足请求所需的数据。

  • It facilitates handling authentication for our API.

    它有助于处理我们API的身份验证

For the sake of learning the basics of Apollo Server, we’re not going to use any of the supported Node.js frameworks. Instead, we’ll be using something that was built by the Apollo team, something really great which will be the base of our learning: Launchpad.

为了学习Apollo Server的基础知识,我们将不使用任何受支持的Node.js框架。 取而代之的是,我们将使用由Apollo团队构建的东西,那些真正伟大的东西,这将是我们学习的基础:启动板。

发射台 (Launchpad)

Launchpad is a project that’s part of the Apollo umbrella of products, and it’s a pretty amazing tool that allows us to write code on the cloud and create a an Apollo Server online, just like we’d run a snippet of code on Codepen, JSFiddle or JSBin.

Launchpad是一个项目,是Apollo产品系列的一部分,它是一个非常了不起的工具,它使我们可以在云上编写代码并在线创建Apollo服务器,就像我们在Codepen,JSFiddle上运行代码段一样或JSBin。

Except that instead of building a visual tool that’s going to be isolated there, and meant just as a showcase or as a learning tool, with Launchpad we create a GraphQL API. It’s going to be publicly accessible.

除了使用构建的演示工具而不是构建将在此处隔离的可视工具(即作为展示工具或学习工具)之外,我们使用Launchpad创建了GraphQL API。 这将是公开可用的。

Every project on Launchpad is called pad and has its GraphQL endpoint URL, like:

Launchpad上的每个项目都称为pad,并具有其GraphQL端点URL,例如:

https://1jzxrj129.lp.gql.zone/graphql

Once you build a pad, Launchpad gives you the option to download the full code of the Node.js app that’s running it, and you just need to run npm install and npm start to have a local copy of your Apollo GraphQL Server.

构建好便笺本后,Launchpad为您提供了下载正在运行它的Node.js应用程序的完整代码的选项,您只需要运行npm installnpm start即可获得Apollo GraphQL Server的本地副本。

To summarize, it’s a great tool to learn, share, and prototype.

总而言之,它是学习,共享和制作原型好工具

Apollo服务器Hello World (The Apollo Server Hello World)

Every time you create a new Launchpad pad, you are presented with the Hello, World! of Apollo Server. Let’s dive into it.

每次创建新的Launchpad pad时 ,都会向您显示Hello,World! Apollo服务器。 让我们开始吧。

First you import the makeExecutableSchema function from graphql-tools.

首先,您从graphql-tools导入makeExecutableSchema函数。

import { makeExecutableSchema } from 'graphql-tools'

This function is used to create a GraphQLSchema object, by providing it a schema definition (written in the GraphQL schema language) and a set of resolvers.

通过提供一个模式定义(以GraphQL模式语言编写)和一组解析器 ,此函数用于创建GraphQLSchema对象。

A schema definition is an template literal string containing the description of our query and the types associated with each field:

模式定义是模板文字字符串,其中包含查询的描述以及与每个字段关联的类型:

const typeDefs = `  type Query {    hello: String  }`

A resolver is an object that maps fields in the schema to resolver functions. It’s able to lookup data to respond to a query.

解析器是将架构中的字段映射到解析器功能的对象。 它能够查找数据以响应查询。

Here is a simple resolver containing the resolver function for the hello field, which simply returns the Hello world! string:

这是一个简单的解析器,其中包含hello字段的resolver函数,该函数仅返回Hello world! 串:

const resolvers = {  Query: {    hello: (root, args, context) => {      return 'Hello world!'    }  }}

Given those two elements, the schema definition and the resolver, we use the makeExecutableSchema function we imported previously to get a GraphQLSchema object, which we assign to the schema const.

给定这两个元素,即模式定义和解析器,我们使用之前导入的makeExecutableSchema函数来获取GraphQLSchema对象,该对象将分配给schema const。

export const schema = makeExecutableSchema({ typeDefs, resolvers })

This is all you need to serve a simple read-only API. Launchpad takes care of the tiny details.

这是所有你需要成为一个简单的只读API。 Launchpad处理细微的细节。

Here is the full code for the simple Hello World example:

这是简单的Hello World示例的完整代码:

import { makeExecutableSchema } from 'graphql-tools'const typeDefs = `  type Query {    hello: String  }`const resolvers = {  Query: {    hello: (root, args, context) => {      return 'Hello world!'    }  }}export const schema = makeExecutableSchema({  typeDefs,  resolvers})

Launchpad provides a great built-in tool to consume the API:

Launchpad提供了一个很棒的内置工具来使用API​​:

And as I said previously, the API is publicly accessible so you just need to login and save your pad.

正如我之前说的,该API可公开访问,因此您只需登录并保存便笺本即可。

I made a pad that exposes its endpoint at https://kqwwkp0pr7.lp.gql.zone/graphql, so let’s try it using curl from the command line:

我制作了一个垫板,以在https://kqwwkp0pr7.lp.gql.zone/graphql处暴露其端点,因此让我们在命令行中使用curl尝试一下:

$ curl \  -X POST \  -H "Content-Type: application/json" \  --data '{ "query": "{ hello }" }' \  https://kqwwkp0pr7.lp.gql.zone/graphql

which successfully gives us the result we expect:

成功地给了我们我们期望的结果:

{  "data": {    "hello": "Hello world!"  }}

在本地运行GraphQL Server (Run the GraphQL Server locally)

We mentioned that anything you create on Launchpad is downloadable, so let’s go on.

我们提到,您在Launchpad上创建的任何内容都可以下载,因此让我们继续。

The package is composed of two files. The first, schema.js is what we have above.

该程序包由两个文件组成。 首先, schema.js是上面的内容。

The second, server.js, was invisible in Launchpad and that is what provides the underlying Apollo Server functionality, powered by Express, the popular Node.js framework.

第二个服务器server.js在Launchpad中不可见,它提供了底层的Apollo Server功能,由流行的Node.js框架Express提供支持。

It is not the simplest example of an Apollo Server setup, so for the sake of explaining, I’m going to replace it with a simpler example (but feel free to study that after you’ve understood the basics).

这不是Apollo Server设置的最简单示例,因此为了说明起见,我将用一个更简单的示例替换它(但在您了解基本知识之后,请随时进行学习)。

您的第一个Apollo Server代码 (Your first Apollo Server code)

First, run npm install and npm start on the Launchpad code you downloaded.

首先,在下载的启动板代码上运行npm installnpm start

The node server we initialized previusly uses nodemon to restart the server when the files change, so when you change the code, the server is restarted with your changes applied.

当文件更改时,我们初始化的节点服务器通常使用nodemon来重新启动服务器,因此,在更改代码时,将应用所做的更改来重新启动服务器。

Add this code in server.js:

将此代码添加到server.js

const express = require('express')const bodyParser = require('body-parser')const { graphqlExpress } = require('apollo-server-express')const { schema } = require('./schema')const server = express()server.use('/graphql', bodyParser.json(), graphqlExpress({ schema }))server.listen(3000, () => {  console.log('GraphQL listening at http://localhost:3000/graphql')})

With just 11 lines, this is much simpler than the server set up by Launchpad, because we removed all the things that made that code more flexible for their needs.

仅用11行,这比Launchpad设置的服务器简单得多,因为我们删除了所有使代码更灵活地满足其需求的内容。

Coding forces you to make tough decisions: how much flexibility do you need now? How important is it to have clean, understandable code that you can pick up six months from now and easily tweak, or pass to other developers and team members so they can be productive in as little time as needed?

编码迫使您做出艰难的决定:您现在需要多少灵活性? 拥有清晰,可理解的代码(从现在起六个月内可以提取并轻松进行调整),或者将其传递给其他开发人员和团队成员,从而使他们可以在短时间内获得生产力,这有多重要?

Here’s what the code does:

代码是这样的:

We first import a few libraries we’re going to use.

我们首先导入一些将要使用的库。

  • express which will power the underlying network functionality to expose the endpoint

    express将为基础网络功能提供动力以暴露端点

  • bodyParser is the Node body parsing middleware

    bodyParser是Node主体解析中间件

  • graphqlExpress is the Apollo Server object for Express

    graphqlExpress是Express的Apollo服务器对象

const express = require('express')const bodyParser = require('body-parser')const { graphqlExpress } = require('apollo-server-express')

Next we import the GraphQLSchema object we created in the schema.js file above as Schema:

接下来,我们将在上面的schema.js文件中创建的GraphQLSchema对象导入为Schema

const { schema } = require('./schema')

Here is some standard Express set, and we just initialize a server on port 3000

这是一些标准的Express集,我们只是在端口3000上初始化服务器

const server = express()

Now we are ready to initialize Apollo Server:

现在我们准备初始化Apollo Server:

graphqlExpress({ schema })

and we pass that as a callback to our endpoint to HTTP JSON requests:

并将其作为回调传递给端点,以传递给HTTP JSON请求:

server.use('/graphql', bodyParser.json(), graphqlExpress({ schema }))

All we need now is to start Express:

现在我们需要启动Express:

server.listen(3000, () => {  console.log('GraphQL listening at http://localhost:3000/graphql')})

添加一个GraphiQL端点 (Add a GraphiQL endpoint)

If you use GraphiQL, you can easily add a /graphiql endpoint, to consume with the GraphiQL interactive in-browser IDE:

如果使用GraphiQL,则可以轻松添加/graphiql端点,以与GraphiQL交互式浏览器内置IDE配合使用

server.use('/graphiql', graphiqlExpress({  endpointURL: '/graphql',  query: ``}))

We now just need to start up the Express server:

现在,我们只需要启动Express服务器:

server.listen(PORT, () => {  console.log('GraphQL listening at http://localhost:3000/graphql')  console.log('GraphiQL listening at http://localhost:3000/graphiql')})

You can test it by using curl again:

您可以再次使用curl进行测试:

$ curl \  -X POST \  -H "Content-Type: application/json" \  --data '{ "query": "{ hello }" }' \  http://localhost:3000/graphql

This will give you the same result as above, where you called the Launchpad servers:

这将为您提供与上述相同的结果,其中您将启动板服务器称为:

{  "data": {    "hello": "Hello world!"  }}

Interested in learning JavaScript? Get my ebook at jshandbook.com

有兴趣学习JavaScript吗? 在jshandbook.com上获取我的电子书

翻译自: https://www.freecodecamp.org/news/a-complete-introduction-to-apollo-the-graphql-toolkit-83acab4b8143/

apollo调试工具

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值