我们正在继电器中形成一个查询。我们的用户数据库设置如下:
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命令时遇到以下错误:
错误:“查询”类型的字段“user”上的未知参数“id”。 文件:App.js 资源: >
查询App {user(id:$ userID)} ^^^
----------------------- enter code here
有人可以帮我们解决这个问题吗?
答案 0 :(得分:3)
您的架构没有为用户字段定义任何参数:
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
}
}