GraphQL LogoGraphQL 中文网

GraphQL.js 入门

先决条件(Prerequisites)#

英:Prerequisites

在开始之前,你应该安装 Node v6,尽管这些示例大部分也应该适用于以前版本的 Node。在本指南中,我们不会使用任何需要转译的语言功能,但我们将使用一些 ES6 功能,例如 Promise粗箭头函数,因此如果你不熟悉它们,你可能需要先阅读它们。

英:Before getting started, you should have Node v6 installed, although the examples should mostly work in previous versions of Node as well. For this guide, we won't use any language features that require transpilation, but we will use some ES6 features like Promises, classes, and fat arrow functions, so if you aren't familiar with them you might want to read up on them first.

要创建一个新项目并在当前目录中安装 GraphQL.js:

英:To create a new project and install GraphQL.js in your current directory:

npm init
npm install graphql --save

编写代码(Writing Code)#

英:Writing Code

为了处理 GraphQL 查询,我们需要一个定义 Query 类型的模式,并且需要一个 API 根,其中每个 API 端点都有一个名为“解析器”的函数。对于只返回“Hello world!”的 API,我们可以将此代码放在名为 server.js 的文件中:

英:To handle GraphQL queries, we need a schema that defines the Query type, and we need an API root with a function called a “resolver” for each API endpoint. For an API that just returns “Hello world!”, we can put this code in a file named server.js:

var { graphql, buildSchema } = require("graphql")
// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
type Query {
hello: String
}
`)
// The rootValue provides a resolver function for each API endpoint
var rootValue = {
hello: () => {
return "Hello world!"
},
}
// Run the GraphQL query '{ hello }' and print out the response
graphql({
schema,
source: "{ hello }",
rootValue,
}).then(response => {
console.log(response)
})

如果你运行此命令:

英:If you run this with:

node server.js

你应该看到打印出的 GraphQL 响应:

英:You should see the GraphQL response printed out:

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

恭喜你 - 你刚刚执行了一个 GraphQL 查询!

英:Congratulations - you just executed a GraphQL query!

对于实际应用,你可能希望从 API 服务器运行 GraphQL 查询,而不是使用命令行工具执行 GraphQL。要将 GraphQL 用于 HTTP 上的 API 服务器,请查看 运行 Express GraphQL 服务器

英:For practical applications, you'll probably want to run GraphQL queries from an API server, rather than executing GraphQL with a command line tool. To use GraphQL for an API server over HTTP, check out Running an Express GraphQL Server.

继续阅读 →运行 Express GraphQL 服务器
GraphQL 中文网 - 粤ICP备13048890号