GraphQL 列表或单个对象
GraphQL List or single object
我得到了以下 "problem"。我已经习惯了那样的 API。
/users
/users/{id}
第一个 return 是一个用户列表。第二个只是一个单一的对象。我想对 GraphQL 也一样,但似乎失败了。我得到以下架构
var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
users: {
type: new GraphQLList(userType),
args: {
id: {type: GraphQLString}
},
resolve: function (_, args) {
if (args.id) {
return UserService.findOne(args.id).then(user => [user]);
} else {
return UserService.find()
}
}
}
}
})
});
如何将用户类型修改为 return 列表或单个对象?
您不应将一个字段用于不同的目的。取而代之的是,制作两个字段。一个用于单个对象,另一个用于对象列表。这是更好的实践和更好的测试
fields: {
user: {
type: userType,
description: 'Returns a single user',
args: {
id: {type: GraphQLString}
},
resolve: function (_, args) {
return UserService.findOne(args.id);
}
},
users: {
type: new GraphQLList(userType),
description: 'Returns a list of users',
resolve: function () {
return UserService.find()
}
}
}
以上回答正确,通常的做法是添加单复数形式的查询。但是,在大型模式中,这可能会重复很多逻辑,并且可以抽象一点,例如使用 Node 接口和节点、节点查询。但是节点查询通常以 ids 作为参数应用(在 Relay 即 node Fields), but you can build your own abstracted way for fetching so that you have just nodes with some argument for type and based on that you can say what type of list to fetch. However, the simpler approach is to just duplicate the logic for every type and use singular and plural form of query and do the same type of queries as above or in this code snippet for every type. For more detail explanation on implementing GraphQL list modifiers in queries or even as an input for mutations. I just published the article 上。
我得到了以下 "problem"。我已经习惯了那样的 API。
/users
/users/{id}
第一个 return 是一个用户列表。第二个只是一个单一的对象。我想对 GraphQL 也一样,但似乎失败了。我得到以下架构
var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
users: {
type: new GraphQLList(userType),
args: {
id: {type: GraphQLString}
},
resolve: function (_, args) {
if (args.id) {
return UserService.findOne(args.id).then(user => [user]);
} else {
return UserService.find()
}
}
}
}
})
});
如何将用户类型修改为 return 列表或单个对象?
您不应将一个字段用于不同的目的。取而代之的是,制作两个字段。一个用于单个对象,另一个用于对象列表。这是更好的实践和更好的测试
fields: {
user: {
type: userType,
description: 'Returns a single user',
args: {
id: {type: GraphQLString}
},
resolve: function (_, args) {
return UserService.findOne(args.id);
}
},
users: {
type: new GraphQLList(userType),
description: 'Returns a list of users',
resolve: function () {
return UserService.find()
}
}
}
以上回答正确,通常的做法是添加单复数形式的查询。但是,在大型模式中,这可能会重复很多逻辑,并且可以抽象一点,例如使用 Node 接口和节点、节点查询。但是节点查询通常以 ids 作为参数应用(在 Relay 即 node Fields), but you can build your own abstracted way for fetching so that you have just nodes with some argument for type and based on that you can say what type of list to fetch. However, the simpler approach is to just duplicate the logic for every type and use singular and plural form of query and do the same type of queries as above or in this code snippet for every type. For more detail explanation on implementing GraphQL list modifiers in queries or even as an input for mutations. I just published the article 上。