- GraphQL Tutorial
- GraphQL - Home
- GraphQL - Introduction
- GraphQL - Environment Setup
- GraphQL - Architecture
- GraphQL - Application Components
- GraphQL - Example
- GraphQL - Type System
- GraphQL - Schema
- GraphQL - Resolver
- GraphQL - Query
- GraphQL - Mutation
- GraphQL - Validation
- GraphQL - JQuery Integration
- GraphQL - React Integration
- GraphQL - Apollo Client
- GraphQL - Authenticating Client
- GraphQL - Caching
- GraphQL Useful Resources
- GraphQL - Quick Guide
- GraphQL - Useful Resources
- GraphQL - Discussion
GraphQL - 查询
GraphQL 操作可以是读取操作,也可以是写入操作。GraphQL 查询用于读取或获取值,而突变用于写入或发布值。无论哪种情况,操作都是一个简单的字符串,GraphQL 服务器可以解析该字符串并使用特定格式的数据进行响应。通常用于移动和 Web 应用程序的流行响应格式是 JSON。
定义查询的语法如下 -
//syntax 1
query query_name{ someField }
//syntax 2
{ someField }
以下是查询的示例 -
//query with name myQuery
query myQuery{
greeting
}
// query without any name
{
greeting
}
从上面的例子可以清楚地看出,查询关键字是可选的。
GraphQL 查询有助于减少数据的过度获取。与 Restful API 不同,GraphQL 允许用户限制应从服务器获取的字段。这意味着更少的查询和更少的网络流量;这反过来又减少了响应时间。
图 1 - 使用自定义字段查询学生模型
在此示例中,我们将一组学生存储在 json 文件中。每个学生模型都有名字、姓氏和 ID 等字段,但没有全名。在这里,我们将讨论如何进行查询来检索所有学生的全名。为此,我们需要在两个模式解析器中创建 fullName 字段。
让我们看看如何使用以下步骤来完成此插图 -
第 1 步 - 下载并安装项目所需的依赖项
创建一个名为query-app的文件夹。从终端将目录更改为query-app 。稍后,按照“环境设置”一章中说明的步骤 3 到 5 进行操作。
第 2 步 - 创建架构
在项目文件夹 query-app 中添加schema.graphql文件并添加以下代码 -
type Query {
greeting:String
students:[Student]
studentById(id:ID!):Student
}
type Student {
id:ID!
firstName:String
lastName:String
fullName:String
}
请注意, students.json文件中没有fullName字段。但是,我们需要通过查询获取学生的全名。在本例中, fullName将是数据源不可用的自定义字段。
第 3 步 - 创建解析器
在项目文件夹中创建文件resolvers.js并添加以下代码 -
const db = require('./db')
const Query = {
//resolver function for greeting
greeting:() => {
return "hello from TutorialsPoint !!!"
},
//resolver function for students returns list
students:() => db.students.list(),
//resolver function for studentbyId
studentById:(root,args,context,info) => {
//args will contain parameter passed in query
return db.students.get(args.id);
}
}
//for each single student object returned,resolver is invoked
const Student = {
fullName:(root,args,context,info) => {
return root.firstName+":"+root.lastName
}
}
module.exports = {Query,Student}
第 4 步 - 运行应用程序
创建一个server.js文件。请参阅环境设置一章中的步骤 8。在终端中执行命令 npm start。服务器将在 9000 端口上启动并运行。在这里,我们使用 GraphiQL 作为客户端来测试应用程序。
打开浏览器并输入 URL http://localhost:9000/graphiql。在编辑器中输入以下查询 -
{
students{
id
fullName
}
}
查询的响应如下 -
{
"data": {
"students": [
{
"id": "S1001",
"fullName": "Mohtashim:Mohammad"
},
{
"id": "S1002",
"fullName": "Kannan:Sudhakaran"
},
{
"id": "S1003",
"fullName": "Kiran:Panigrahi"
}
]
}
}
创建一个server.js并添加以下代码 -
const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const db = require('./db');
const port = 9000;
const app = express();
//loading type definitions from schema file
const fs = require('fs')
const typeDefs = fs.readFileSync('./schema.graphql',{encoding:'utf-8'})
//loading resolvers
const resolvers = require('./resolvers')
//binding schema and resolver
const {makeExecutableSchema} = require('graphql-tools')
const schema = makeExecutableSchema({typeDefs, resolvers})
//enabling cross domain calls and form post
app.use(cors(), bodyParser.json());
//enabling routes
const {graphiqlExpress,graphqlExpress} = require('apollo-server-express')
app.use('/graphql',graphqlExpress({schema}))
app.use('/graphiql',graphiqlExpress({endpointURL:'/graphql'}))
//registering port
app.listen(port, () => console.info(`Server started on port ${port}`));
在终端中执行命令 npm start。服务器将在 9000 端口上启动并运行。在这里,我们使用 GraphiQL 作为客户端来测试应用程序。
打开浏览器并输入 URL http://localhost:9000/graphiql。在编辑器中输入以下查询 -
{
students{
id
fullName
}
}
查询的响应如下 -
{
"data": {
"students": [
{
"id": "S1001",
"fullName": "Mohtashim:Mohammad"
},
{
"id": "S1002",
"fullName": "Kannan:Sudhakaran"
},
{
"id": "S1003",
"fullName": "Kiran:Panigrahi"
}
]
}
}
图 2 - 嵌套查询
让我们创建一个嵌套查询来获取学生详细信息及其大学详细信息。我们将使用相同的项目文件夹。
第 1 步 - 编辑架构
模式文件已经具有学生字段。让我们添加一所野外学院并定义其类型。
type College {
id:ID!
name:String
location:String
rating:Float
}
type Student {
id:ID!
firstName:String
lastName:String
fullName:String
college:College
}
步骤 2 - 修改resolver.js
我们需要添加一个大学解析器函数,如下所示。将为每个返回的学生对象执行大学解析器函数。在这种情况下,解析器的根参数将包含Student。
const Student = {
fullName:(root,args,context,info) => {
return root.firstName+":"+root.lastName
},
college:(root) => {
return db.colleges.get(root.collegeId);
}
}
module.exports = {Query,Student}
解析器通过调用 College 集合的 get 方法并传递 CollegeId 返回每个学生的College。我们通过CollegeId建立 Student 和 College 之间的关联关系。
第 3 步 - 测试应用程序
打开终端窗口并导航到项目文件夹。键入命令 -npm start。启动浏览器并输入 URL http://localhost:9000/graphiql。
在 GraphiQL 窗口中输入以下查询 -
{
students{
id
firstName
college {
id
name
location
rating
}
}
}
查询的响应如下 -
{
"data": {
"students": [
{
"id": "S1001",
"firstName": "Mohtashim",
"college": {
"id": "col-102",
"name": "CUSAT",
"location": "Kerala",
"rating": 4.5
}
},
{
"id": "S1002",
"firstName": "Kannan",
"college": {
"id": "col-101",
"name": "AMU",
"location": "Uttar Pradesh",
"rating": 5
}
},
{
"id": "S1003",
"firstName": "Kiran",
"college": {
"id": "col-101",
"name": "AMU",
"location": "Uttar Pradesh",
"rating": 5
}
}
]
}
}
什么是查询变量?
如果查询需要传递一些动态值,则使用变量表示这些动态值。因此,客户端应用程序可以重用该查询。
插图
让我们创建一个简单的应用程序来理解查询变量。
第 1 步 - 编辑架构文件
添加一个sayHello字段,它接受一个字符串参数并返回一个字符串。名称值在客户端应用程序中将是动态的。
type Query {
sayHello(name:String!):String
}
步骤 2 - 编辑resolver.js 文件
添加一个sayHello解析器,其参数如下 -
sayHello:(root,args,context,info) => `Hi ${args.name} GraphQL server says Hello to you!!`
步骤 3 - 在 GraphiQL 中声明查询变量
变量用 $ 后跟变量名称来声明。例如:$myname_Variable。
一旦声明 $myname_Variable,它就必须与命名查询语法一起使用。查询 myQuery 获取字符串值并将其传递给 sayHello,如下所示 -
query myQuery($myname_Variable:String!) {
sayHello(name:$myname_Variable)
}
在 GraphiQL 客户端的查询变量部分将 $myname_Variable 的值设置为 JSON 对象。
{
"myname_Variable": "Mohtashim"
}
上述代码的输出如下 -
{
"data": {
"sayHello": "Hi Mohtashim GraphQL server says Hello to you!!"
}
}
如何将查询变量与枚举一起使用
让我们看看当字段参数是枚举类型时如何使用查询变量。
步骤 1 - 编辑 schema.graphql 文件
enum ColorType {
RED
BLUE
GREEN
}
type Query {
setFavouriteColor(color:ColorType):String
}
setFavouriteColor函数将枚举作为输入并返回一个字符串值。
步骤 2 - 编辑resolvers.js 文件
解析器函数setFavouriteColor采用root和args。运行时传递给函数的枚举值可以通过 args 参数访问。
setFavouriteColor:(root,args) => {
return "Your Fav Color is :"+args.color;
}
步骤 3 - 在 GraphiQL 中声明查询变量
该查询名为query_to_setColor,它采用 ColorType 的名称 color_variable 的变量。该变量被传递给方法 setFavouriteColor。
query query_to_setColor($color_variable:ColorType) {
setFavouriteColor(color:$color_variable)
}
在 GraphiQL 的查询变量部分中,输入以下代码 -
{
"color_variable":"RED"
}
响应如下所示 -
{
"data": {
"setFavouriteColor": "Your Fav Color is: RED"
}
}
