9. 执行GraphQL查询

我们已经了解了GraphQL查询语言以及如何定义schema。 但还未尝试对自己的schema执行查询。为了完成这个目标,我们可以使用GraphQL Sandbox,它是基于Facebook的GraphQL项目开发的。

现在你就要学习如何运行GraphQL schema了。本课中,我们将使用NodeJS(和JavaScript)来进行查询,其他语言的实现将在后面的课程里学习到。

使用“graphql”npm模块

graphqlnpm模块是定义一个基本schema并对其执行查询所需的唯一工具(或库)。

让我们开始吧!


准备工作

首先,创建一个目录来放置JavaScript文件和npm模块。

mkdir hello-graphql
cd hello-graphql
# this will create a `package.json` file for this directory
npm init -f

我们将在这个项目中使用ES2015,因此请务必在你的机器上安装babelcli。

npm install -g babel-cli

然后我们需要为babel添加ES2015支持。 (港真,其实就是为我们的包中安装babel预设。)

npm install babel-preset-es2015 --save

然后创建一个index.js文件,它是我们定义schema的地方。

touch index.js

然后,可以执行这个命令啦:babel-node index.js

在这里,我们使用babel-node,因为它能将ES2015转换为ES5并且执行应用程序,而不管你安装的是何种版本的nodejs。

最后,将graphqlnpm模块安装到此目录中。

npm install graphql --save

定义schema

现在我们需要定义一个schema。 在这个schema中,我们仅有一个名为echo的根查询字段,它的作用是回显接收到的内容。

导入GraphQL类

首先,需要导入所有的GraphQL基本类型,我们将用它来构造schema。 接下来,在我们的index.js文件头部添加以下内容:

import {
  // These are the basic GraphQL types
  GraphQLInt,
  GraphQLFloat,
  GraphQLString,
  GraphQLList,
  GraphQLObjectType,
  GraphQLEnumType,

  // This is used to create required fields and arguments
  GraphQLNonNull,

  // This is the class we need to create the schema
  GraphQLSchema,

  // This function is used execute GraphQL queries
  graphql
} from 'graphql';

接下来是我们的schema:

const Query = new GraphQLObjectType({
  name: 'RootQueries',
  fields: () => ({
    echo: {
      type: GraphQLString,
      args: {
        message: {type: GraphQLString}
      },
      resolve(rootValue, args) {
        return `received: ${args.message}`;
      }
    }
  })
});

const Schema = new GraphQLSchema({
  query: Query
});

现在尝试运行index.js文件:

babel-node index.js --presets "es2015"

如果一切正常的话,命令执行后将不会在控制台里打印出任何消息。


执行查询

现在可以执行查询了,所以,首先让我们把这个查询赋给一个变量。

将此内容添加到index.js文件的末尾:

let query = `
  {
    receivedMessage: echo(message: "Hello")
  }
`;

然后执行此查询:

graphql(Schema, query).then(function(result) {
  console.log(result);
});

这里,我们使用graphql模块中的graphql函数来实现查询,它返回一个promise,所以,我们在.then里输出得到的结果。

执行我们的脚本:

babel-node index.js --presets "es2015"

然后会在控制台上得到这样的结果:

{ data: { receivedMessage: 'received: Hello' } }

分配查询变量

现在我们需要在查询中引入查询变量了,代码如下所示:

let query = `
  query getEcho($inputMessage: String) {
    receivedMessage: echo(message: $inputMessage)
  }
`;

然后,我们为graphql函数提供查询变量:

graphql(Schema, query, null, {inputMessage: "Hello"}).then(function(result) {
  console.log(result);
});

接着,运行脚本:babel-node index.js --presets“es2015”

yes!你就会看到预期的结果啦~


现在有一个任务。

运行下方的查询,但不提供任何查询变量。

graphql(Schema, query, null).then(function(result) {
  console.log(result);
});

会发生什么呢?

  • There was an error saying: query variables are required.
  • There was nothing in the console.
  • We got the result as: received: undefined.
  • We got the result as: received: null.

即使没有查询变量,我们的查询命令也能顺利执行,虽然只能得到received: undefined的输出结果。这是因为message是根查询的可选字段。

如果它是必填字段的话,就会抛出错误了。


下一步是什么

通过这节课,我们学会了用一个非常基本的方法来执行GraphQL查询。 graphqlnpm模块是同构的,所以在客户端和服务器都能使用。

当在一个真正的应用程序里使用graphql模块时,你可以从生成GraphQL schema的高级模块来获得更多帮助,比如:

  • express-graphql - 你可以在该项目里用express来创建GraphQL服务。

  • graffiti- 该项目可以使用GraphQL已有的mongoose模式。

results matching ""

    No results matching ""