如何在 GraphQL 中制定嵌套模式
Posted
技术标签:
【中文标题】如何在 GraphQL 中制定嵌套模式【英文标题】:How to formulate nested schema in GraphQL 【发布时间】:2021-11-27 23:45:06 【问题描述】:我是 GraphQL 的新手。作为实验,我运行了以下 Node.js Express 服务器:
var express = require('express');
var graphqlHTTP = require('express-graphql');
var buildSchema = require('graphql');
var schema = buildSchema(`
type Student
sid: ID,
name: String,
subjects: [String!],
address: Location
type Location
unit: String,
city: String,
country: String,
postCode: Int
`);
var root = // The root provides a resolver function for each API endpoint
address: () => (
city: ()=>'London'
),
;
var app = express();
app.use('/graphql', graphqlHTTP(
schema: schema,
rootValue: root,
graphiql: true,
));
app.listen(4000);
console.log('Running a GraphQL API server at http://localhost:4000/graphql');
当我在浏览器的界面上运行以下查询时:
address
city
我遇到了一个错误:
"errors": [
"message": "Query root type must be provided."
]
这样做的正确方法应该是什么?
【问题讨论】:
【参考方案1】:事实证明,我必须为入口点定义模式“Query”(以及可选的“Mutation”)。
var express = require('express');
var graphqlHTTP = require('express-graphql');
var buildSchema = require('graphql');
var fakeDatabase = [sid:parseInt(Math.random()*10000),
name:'Philip',
subjects:['Chemistry', 'Physics', 'Maths'],
address:
unit: 'H505',
city: 'London',
country: 'United Kingdom',
postCode: 33100
];
// 'Query' and 'Mutation' are special schemas defining the entry points
var schema = buildSchema(`
type Query
name: String
sid(year: Int): ID
subjects: [String]
address: Location
type Location
unit: String
city: String
country: String
postCode: Int
type Mutation
setName(nn: String): String
`);
// Each field is either a constant or a callback
var root =
name: ()=>fakeDatabase[0].name,
sid: arg => (arg.year+"-"+fakeDatabase[0].sid),
subjects: fakeDatabase[0].subjects,
address: () => (
city: ()=>fakeDatabase[0].address.city
),
setName: arg => fakeDatabase[0].name=arg.nn; return arg.nn;
;
var app = express();
app.use('/graphql', graphqlHTTP(
schema: schema,
rootValue: root,
graphiql: true,
));
app.listen(4000);
console.log('Running a GraphQL API server at http://localhost:4000/graphql');
【讨论】:
以上是关于如何在 GraphQL 中制定嵌套模式的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 reactjs 和 graphql 在 gatsby 中映射嵌套数组
如何使用 gatsby-source-prismic 在 graphql 中执行嵌套查询