2

我们正在中继中形成一个查询。我们的用户数据库设置如下:


function User(id, name, des) {
  this.id = id.toString()
  this.name = name
  this.des = des
}

var users = [new User(1, 'abc', 'Hello abc'), new User(2, 'xyz', 'Hello xyz')]

module.exports = {
  User: User,
  getAnonymousUser: function() {return users[0] }
}

我们的 schema.js 文件如下:

var nodeDefinitions = GraphQLRelay.nodeDefinitions(function(globalId) {
  var idInfo = GraphQLRelay.fromGlobalId(globalId)
  if (idInfo.type == 'User') {
    return db.getUser(idInfo.id)
  } 
  return null
})


var userType = new GraphQL.GraphQLObjectType({
  name: 'User',
  description: 'A person who uses our app',
  isTypeOf: function(obj) { return obj instanceof db.User },

  fields: function() {
    return {
      id: GraphQLRelay.globalIdField('User'),
      des: {
        type: GraphQL.GraphQLString,
        description: 'The des of the user',
      },
      name: {
        type: GraphQL.GraphQLString,
        description: 'The name of the user',
      }
    }
  },
  interfaces: [nodeDefinitions.nodeInterface],
})

module.exports = new GraphQL.GraphQLSchema({
  query: new GraphQL.GraphQLObjectType({
    name: 'Query',
    fields: {
      node: nodeDefinitions.nodeField,
      user: {
        type: userType,
        resolve: function() { return db.getAnonymousUser() },
      },
    },
  }),
})

我们创建了我们的中继容器:

exports.Container = Relay.createContainer(App, {
  fragments: {
    user: () => Relay.QL`
        fragment on User {
            name
        }
    `,
  },
})

exports.queries = {
  name: 'AppQueries',
  params: { 
   userID: '1',
  },
  queries: {
    //user: () => Relay.QL`query { user }`,
    user: () => Relay.QL `query { user(id: $userID) }`
  },
}

但是我们无法通过 userId 获取用户,并且在运行 npm run build 命令时出现以下错误:

错误:“查询”类型的字段“用户”上的未知参数“id”。文件:App.js 来源:>

查询应用{用户(id:$userID)}^^^

----------------------enter code here

有人可以在这个问题上帮助我们吗?

4

1 回答 1

4

您的架构没有为用户字段定义任何参数:

 user: {
   type: userType,
   resolve: function() { return db.getAnonymousUser() },
 },

要按 ID 获取用户,请定义id参数,然后按该 ID 获取用户:

user: {
  args: {
    id: { type: GraphQLString }
  },
  resolve: function(root, args) {
    return db.findUserById(args.id); // you don't have this method but it's an example of how to use the arg
  }
}
于 2015-12-09T17:28:57.370 回答