📜  GraphQL-模式

📅  最后修改于: 2020-10-25 05:09:28             🧑  作者: Mango


 

GraphQL模式是任何GraphQL服务器实现的核心。它描述了连接到它的客户端应用程序可用的功能。我们可以使用任何编程语言来创建GraphQL模式并围绕它构建接口。

GraphQL运行时定义了一个基于图形的通用架构,以发布其表示的数据服务的功能。客户端应用程序可以在其功能范围内查询架构。这种方法使客户端与服务器脱钩,并允许它们独立发展和扩展。

在本章中,我们使用Apollo服务器执行GraphQL查询。 graphql-tools中的makeExecutableSchema函数可帮助您绑定架构和解析器。

makeExecutableSchema函数语法

makeExecutableSchema函数采用对象类型的单个参数{}。下面给出了使用此函数的语法-

import { makeExecutableSchema } from 'graphql-tools';

const jsSchema = makeExecutableSchema({
   typeDefs,
   resolvers, // optional
   logger, // optional
   allowUndefinedInResolve = false, // optional
   resolverValidationOptions = {}, // optional
   directiveResolvers = null, // optional
   schemaDirectives = null,  // optional
   parseOptions = {},  // optional
   inheritResolversFromInterfaces = false  // optional
});    
Sr.No. Parameter & Description
1 typeDefs

This is a required argument. It represents a GraphQL query as a UTF-8 string.

2 Resolvers

This is an optional argument (empty object by default). This has functions that handle the query.

3 logger

This is an optional argument and can be used to print errors to the server console.

4 parseOptions

This is an optional argument and allows customization of parse when specifying typeDefs as a string.

5 allowUndefinedInResolve

This is true by default. When set to false, causes your resolve functions to throw errors if they return undefined.

6 resolverValidationOptions

This is an optional argument and accepts an object with Boolean properties.

7 inheritResolversFromInterfaces

This is an optional argument and accepts a Boolean argument to check resolvers object inheritance.

插图

让我们创建一个简单的应用程序以了解此架构。这将创建一个模式,用于从服务器查询学生列表。学生数据将存储在一个平面文件中,我们将使用一个名为notarealdb的节点模块来伪造数据库并从该平面文件中读取数据。

步骤1-下载并安装项目的必需依赖项

创建一个名为schema-app的文件夹。从终端将目录更改为schema-app。然后,按照“环境设置”一章中介绍的步骤3至5来完成下载和安装过程。

第2步-创建架构

在项目文件夹schema-app中添加schema.graphql文件,并添加以下代码-

type Query {
   greeting:String
   students:[Student]
}

type Student {
   id:ID!
   firstName:String
   lastName:String
   password:String
   collegeId:String
}

模式的根将是查询类型。该查询有两个字段-Greeting和Students,分别返回String和学生列表。学生被声明为对象类型,因为它包含多个字段。 ID字段声明为不可为空。

第3步-创建解析器

在项目文件夹中创建文件resolvers.js并添加以下代码-

const db = require('./db')
const Query = {
   greeting:() => {
      return "hello from  TutorialsPoint !!!"
   },
   students:() => db.students.list()
}

module.exports = {Query}

问候语和学生是处理查询的解析器。学生解析器函数从数据访问层返回学生列表。要访问模块外部的解析器功能,必须使用module.exports导出查询对象。

步骤4-运行应用程序

创建一个server.js文件,并参考环境设置一章中的步骤8。下一步是在终端中执行命令npm start。服务器将启动并在9000端口上运行。在这里,我们使用GraphiQL作为客户端来测试应用程序。打开浏览器,然后输入URL http:// localhost:9000 / graphiql

在编辑器中键入以下查询-

{
   greeting
   students {
      id
      firstName
      lastName
   }
}

查询将显示输出,如下所示-

查询输出

注意-我们可以使用RESTful API调用替换students.json来检索学生数据,甚至检索真实的数据库(如MySQL或MongoDB)。 GraphQL变成原始应用程序层的薄包装,以提高性能。