Getting error : Unknown argument “id” on field “us

2019-07-13 03:02发布

问题:

We are forming a query in relay. We have user database set as follows:


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] }
}

Our schema.js file is as follows:

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() },
      },
    },
  }),
})

we have created our relay container as:

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) }`
  },
}

But we are not able to get the user by userId and getting following error on running npm run build command:

Error: Unknown argument "id" on field "user" of type "Query". File: App.js Source: >

query App { user(id: $userID) } ^^^

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

Can someone help us on this issue?

回答1:

Your schema doesn't define any arguments for the user field:

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

To fetch user by ID, define the id argument, and fetch the user by that 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
  }
}