因此,据我所知,GraphQL网站上有S#* t文档,例如关于用户特殊性的嵌套查询,它使我发疯(我现在很想把我的头发拔出来)。有人可以向我解释一下左轮手枪是如何工作的,为什么我的工作不起作用吗?
问题: 我为GraphQL API创建了以下index.js文件:
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
// Define Schemas
var schema = buildSchema(`
type Query {
user: User
}
type User {
firstName: String
lastName: String
email: String
socialMedia: SOCIALMEDIA
}
type SOCIALMEDIA {
facebook: String
instagram: String
twitter: String
}
`);
// Define resolver functions
var root = {
User: {
firstName: () => 'John',
lastName: () => 'Doe',
email: () => 'John.Doe@gmail.com'
},
SOCIALMEDIA: {
facebook: () => 'John Doe Facebook',
instagram: () => 'John Doe Instagram',
twitter: () => 'John Doe Twitter'
}
};
var app = express();
app.use('/', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(8080, () => console.log('Now browse to localhost:8080'));
尽管我已尽力而为,但当我提交以下查询时:
{
user {
firstName
}
}
我得到以下答案:
{
"data": {
"user": null
}
}
为什么是null
?!?!我什至都没有尝试过user(id: $ID): [User]
迭代或任何类似于传递参数或函数的事情,甚至已经让我坚持不懈!
关于嵌套字段的工作方式我缺少什么?
编辑: 哇...好了吗?
user: () => ({
firstName: 'John',
lastName: 'Doe',
email: 'John.Doe@gmail.com',
socialMedia: {
facebook: 'John Doe Facebook',
instagram: 'John Doe Instagram',
twitter: 'John Doe Twitter'
}
}),
这种胡说八道的硬性规定是什么?
答案 0 :(得分:0)
尝试一下
// Define Schemas
var schema = buildSchema(`
type Query {
getUser: User
getSocialMedia: SOCIALMEDIA
}
type User {
firstName: String
lastName: String
email: String
socialMedia: SOCIALMEDIA
}
type SOCIALMEDIA {
facebook: String
instagram: String
twitter: String
}
`);
// Define resolver functions
var root = {
getUser: {
firstName: () => 'John',
lastName: () => 'Doe',
email: () => 'John.Doe@gmail.com',
socialMedia: {
facebook: () => 'John Doe Facebook',
instagram: () => 'John Doe Instagram',
twitter: () => 'John Doe Twitter'
}
},
getSocialMedia: {
facebook: () => 'John Doe Facebook',
instagram: () => 'John Doe Instagram',
twitter: () => 'John Doe Twitter'
}
};