0

我只是致力于将公司与用户联系起来。我在用户类型上创建了一个新的公司字段,并告诉它它将是 type CompanyType

我的下一步是在这个属性上定义一个解析函数,以便 GraphQL 知道如何找到与给定用户关联的公司。

所以我在这里的目标是找到一个用户并找到他们的关联公司。我想教 GraphQL 如何从用户走到公司。

这是我写的代码:

const graphql = require('graphql');
const axios = require('axios');
const { GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLSchema } = graphql;

const CompanyType = new GraphQLObjectType({
  name: 'Company',
  fields: {
    id: { type: GraphQLString },
    name: { type: GraphQLString },
    description: { type: GraphQLString }
  }
});

const UserType = new GraphQLObjectType({
  name: 'User',
  fields: {
    id: { type: GraphQLString },
    firstName: { type: GraphQLString },
    age: { type: GraphQLInt },
    company: {
      type: CompanyType,
      resolve(parentValue, args) {
        console.log(parentValue, args);
      }
    }
  }
});

const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    user: {
      type: UserType,
      args: { id: { type: GraphQLString } },
      resolve(parentValue, args) {
        return axios
          .get(`http://localhost:3000/users/${args.id}`)
          .then(res => res.data);
      }
    }
  }
});

module.exports = new GraphQLSchema({
  query: RootQuery
});

我的期望console.log(parentValue, args);是在控制台中得到这个输出:

`{ id: '23', firstName: 'Bill', age: 20, companyID: '1' } {}`

在我去 graphiQL 并点击播放按钮后请求这个:

{
    user(id: "23") {
    firstName
    company {
      id
    }
  }
}

相反,我在控制台中得到的输出是这样的:

{ id: '23', firstName: 'Bill', age: 20 } {}

我不确定为什么我在教授 GraphQL 如何获取这些数据以使用 resolve 函数填充该公司属性时没有成功。请帮忙。

4

0 回答 0