如何正确编写 GraphQL 解析器?

How to write GraphQL Resolvers properly?

所以 GraphQL 站点有 S#*t 文档,据我所知关于嵌套查询,如用户 specifics 和它让我发疯(我现在真的想把我的头发拉出来)。有人可以向我解释一下左轮手枪的工作原理以及为什么我所做的不起作用吗?

问题: 我为我的 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'
        }
    }),

这种废话的硬性规定是什么?

试试这个,

// 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'
    }

 };