node graphql
Start by creating a new Node.js project, if you haven’t one already set up:
首先创建一个新的Node.js项目(如果尚未设置):
npm init --y
This command creates the package.json
file we need to work with npm
.
此命令创建我们需要使用npm
的package.json
文件。
Install the npm packages express
, graphql
and express-graphql
:
安装npm软件包express
, graphql
和express-graphql
:
npm install express graphql express-graphql
Create an app.js
file, and let’s start with the initializing the Express server:
创建一个app.js
文件,让我们从初始化Express服务器开始:
const express = require('express')
const app = express()
app.listen(3000, () => {
console.log('App listening on port 3000')
})
Now we add express-graphql
. This is a middleware, and we apply it to just a route, the /graphql
route:
现在我们添加express-graphql
。 这是一个中间件 ,我们将其仅应用到/graphql
路由:
const express = require('express')
const graphqlHTTP = require('express-graphql')
const app = express()
app.use('/graphql', graphqlHTTP())
app.listen(3000, () => {
console.log('App listening on port 3000')
})
We must pass an object which contains the schema
property, which must contain a schema definition.
我们必须传递一个包含schema
属性的对象,该对象必须包含一个schema定义。
We must define a schema first!
我们必须先定义一个模式!
Create a schema.js
file, and in there we first require graphql
, then using the object destructuring syntax we get the GraphQLSchema
, GraphQLObjectType
and GraphQLString
objects we’ll soon need to use:
创建一个schema.js
文件,在这里我们首先需要graphql
,然后使用对象 GraphQLSchema
语法 ,我们将很快需要使用GraphQLSchema
, GraphQLObjectType
和GraphQLString
对象:
const graphql = require('graphql')
const { GraphQLSchema, GraphQLObjectType, GraphQLString } = graphql
Then we define the schema value by initializing a new GraphQLSchema
instance, passing an object which contains a query
property. This property is an instance of a GraphQLObjectType
object:
然后,我们通过初始化一个新的GraphQLSchema
实例并传递一个包含query
属性的对象来定义架构值。 此属性是GraphQLObjectType
对象的实例:
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
//...
}),
})
module.exports = schema
Inside this new object we must specify a name
, and a fields
parameters. This last property is an object which contains a set of properties, one for each field of our schema. In this example we set up an hello
field:
在这个新对象中,我们必须指定一个name
和一个fields
参数。 最后一个属性是一个对象,其中包含一组属性,每个属性对应于架构的每个字段。 在此示例中,我们设置了一个hello
字段:
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
hello: {
type: GraphQLString,
resolve() {
return 'world'
},
},
},
}),
})
The resolve()
method returns the string world
, which means that when we will ask for the hello
field, we’ll get that string back.
resolve()
方法返回字符串world
,这意味着当我们请求hello
字段时,我们将获得该字符串。
Here is the full schema.js
file content:
这是完整的schema.js
文件内容:
const graphql = require('graphql')
const { GraphQLSchema, GraphQLObjectType, GraphQLString } = graphql
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
hello: {
type: GraphQLString,
resolve() {
return 'world'
},
},
},
}),
})
module.exports = schema
Now let’s go back to our app.js
file.
现在让我们回到我们的app.js
文件。
This is what we had:
这就是我们所拥有的:
const express = require('express')
const graphqlHTTP = require('express-graphql')
const app = express()
app.use('/graphql', graphqlHTTP())
app.listen(3000, () => {
console.log('App listening on port 3000')
})
We now require the schema.js
file:
现在,我们需要schema.js
文件:
const schema = require('./schema.js')
and we add that in an object we pass to the graphqlHTTP()
constructor:
并将其添加到对象中,然后传递给graphqlHTTP()
构造函数:
app.use(
'/graphql',
graphqlHTTP({
schema: schema,
})
)
Ok!
好!
We can now test this and see if it works. We can use GraphiQL, a great tool to test our GraphQL API.
现在,我们可以对其进行测试,看看它是否有效。 我们可以使用GraphiQL ,它是测试GraphQL API的出色工具。
It’s already installed and to enable that, we need to pass another property to the graphqlHTTP
constructor:
它已经安装并启用,我们需要将另一个属性传递给graphqlHTTP
构造函数:
app.use(
'/graphql',
graphqlHTTP({
schema: schema,
graphiql: true,
})
)
Now after you run node app.js
, accessing the http://localhost:3000/graphql
URL with the browser you’ll see GraphiQL in action:
现在,在运行node app.js
,使用浏览器访问http://localhost:3000/graphql
URL,您将看到GraphiQL发挥作用:

And you can test the first API call, passing this query:
您可以通过以下查询来测试第一个API调用:
{
hello
}
This is the result:
结果如下:
Let’s now build a more complex schema.
现在让我们构建一个更复杂的模式。
One that has nested types.
一种具有嵌套类型。
An example I have in mind is a blog post.
我想到的一个例子是博客文章。
A blog post has a title, a description, and it also has an author. The author has a name.
博客文章具有标题,描述以及作者。 作者有一个名字。
Let’s figure this out.
让我们弄清楚这一点。
First we add the set of posts and authors:
首先,我们添加一组帖子和作者:
const posts = [
{
title: 'First post',
description: 'Content of the first post',
author: 'Flavio',
},
{
title: 'Second post',
description: 'Content of the second post',
author: 'Roger',
},
]
const authors = {
Flavio: {
name: 'Flavio',
age: 36,
},
Roger: {
name: 'Roger',
age: 7,
},
}
This is where we’ll get the data from.
这是我们从中获取数据的地方。
Next, we define 3 GraphQLObjectType
instances:
接下来,我们定义3个GraphQLObjectType
实例:
authorType
, which defines the author dataauthorType
,它定义作者数据postType
, which defines the post datapostType
,它定义发布数据queryType
, the main onequeryType
,主要的
Let’s start with the author. An author has a name and an age.
让我们从作者开始。 作者有名字和年龄。
We use the GraphQLInt
type, which we must add to the require:
我们使用GraphQLInt
类型,必须将其添加到需求中:
const { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLInt } = graphql
//...
const authorType = new GraphQLObjectType({
name: 'Author',
fields: {
name: {
type: GraphQLString,
},
age: {
type: GraphQLInt,
},
},
})
Next is postType
. A post has a title, a description (both strings) and an author. An author is of type authorType
, which we just defined, and it has a resolver.
接下来是postType
。 帖子具有标题,描述(两个字符串)和作者。 作者的类型为authorType
,我们刚刚定义了它,并且它具有解析器。
We get the author name from the source
parameter, which is the params passed to the post object, and we lookup the author data based on that. We return it.
我们从source
参数获取作者名称,该参数是传递给post对象的参数,然后基于该参数查找作者数据。 我们退货。
const postType = new GraphQLObjectType({
name: 'Post',
fields: {
title: {
type: GraphQLString,
},
description: {
type: GraphQLString,
},
author: {
type: authorType,
resolve: (source, params) => {
return authors[source.author]
},
},
},
})
Note that a resolver function can be async, so you can use async/await to lookup resources from a database or the network.
请注意,解析程序功能可以是异步的,因此您可以使用async / await从数据库或网络中查找资源。
Next up is queryType, the root type we’ll add to the schema. In there, we define 2 fields:
接下来是queryType,这是我们将添加到架构中的根类型。 在其中,我们定义2个字段:
post
a single blog post, identified by an idpost
一个由ID标识的博客文章posts
the list of postsposts
列表
both of them have a resolver function to lookup the data in the posts
array:
它们都有解析器功能来查找posts
数组中的数据:
const queryType = new GraphQLObjectType({
name: 'Query',
fields: {
post: {
type: postType,
args: {
id: { type: GraphQLInt },
},
resolve: (source, { id }) => {
return posts[id]
},
},
posts: {
type: new GraphQLList(postType),
resolve: () => {
return posts
},
},
},
})
Notice the new GraphQLList
type, which we use to wrap postType
to mean that it’s a list of postType
objects. We must require it on top:
注意新的GraphQLList
类型,我们用它包装postType
表示它是postType
对象的列表。 我们必须首先要求它:
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLList,
GraphQLInt,
} = graphql
That’s it. We need to add it to our schema
and we are set:
而已。 我们需要将其添加到我们的schema
,并设置为:
const schema = new GraphQLSchema({
query: queryType,
})
Here’s the full code:
这是完整的代码:
const graphql = require('graphql')
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLList,
GraphQLInt,
} = graphql
const posts = [
{
title: 'First post',
description: 'Content of the first post',
author: 'Flavio',
},
{
title: 'Second post',
description: 'Content of the second post',
author: 'Roger',
},
]
const authors = {
Flavio: {
name: 'Flavio',
age: 36,
},
Roger: {
name: 'Roger',
age: 7,
},
}
const authorType = new GraphQLObjectType({
name: 'Author',
fields: {
name: {
type: GraphQLString,
},
age: {
type: GraphQLInt,
},
},
})
const postType = new GraphQLObjectType({
name: 'Post',
fields: {
title: {
type: GraphQLString,
},
description: {
type: GraphQLString,
},
author: {
type: authorType,
resolve: (source, params) => {
return authors[source.author]
},
},
},
})
const queryType = new GraphQLObjectType({
name: 'Query',
fields: {
post: {
type: postType,
args: {
id: { type: GraphQLInt },
},
resolve: (source, { id }) => {
return posts[id]
},
},
posts: {
type: new GraphQLList(postType),
resolve: () => {
return posts
},
},
},
})
const schema = new GraphQLSchema({
query: queryType,
})
module.exports = schema
See the complete code on Glitch.
node graphql