我遵循与提及here
相同的架构我想获取所有用户,因此我更新了我的架构
var Root = new GraphQLObjectType({
name: 'Root',
fields: () => ({
user: {
type: userType,
resolve: (rootValue, _) => {
return getUser(rootValue)
}
},
post: {
type: postType,
args: {
...connectionArgs,
postID: {type: GraphQLString}
},
resolve: (rootValue, args) => {
return getPost(args.postID).then(function(data){
return data[0];
}).then(null,function(err){
return err;
});
}
},
users:{
type: new GraphQLList(userType),
resolve: (root) =>getUsers(),
},
})
});
在database.js中
export function getUsers(params) {
console.log("getUsers",params)
return new Promise((resolve, reject) => {
User.find({}).exec({}, function(err, users) {
if (err) {
resolve({})
} else {
resolve(users)
}
});
})
}
我在/ graphql中获得结果
{
users {
id,
fullName
}
}
和结果
{
"data": {
"users": [
{
"id": "VXNlcjo1Nzk4NWQxNmIwYWYxYWY2MTc3MGJlNTA=",
"fullName": "Akshay"
},
{
"id": "VXNlcjo1Nzk4YTRkNTBjMWJlZTg1MzFmN2IzMzI=",
"fullName": "jitendra"
},
{
"id": "VXNlcjo1NzliNjcyMmRlNjRlZTI2MTFkMWEyMTk=",
"fullName": "akshay1"
},
{
"id": "VXNlcjo1NzliNjgwMDc4YTYwMTZjMTM0ZmMxZWM=",
"fullName": "Akshay2"
},
{
"id": "VXNlcjo1NzlmMTNkYjMzNTNkODQ0MmJjOWQzZDU=",
"fullName": "test"
}
]
}
}
但如果我尝试在视图中获取此内容
export default Relay.createContainer(UserList, {
fragments: {
userslist: () => Relay.QL`
fragment on User @relay(plural: true) {
fullName,
local{
email
},
images{
full
},
currentPostCount,
isPremium,
}
`,
},
});
我收到错误Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.
请告诉我我错过了什么。 我和@relay一起尝试过很多次(复数:true)。 还尝试使用参数更新模式
users:{
type: new GraphQLList(userType),
args: {
names: {
type: GraphQLString,
},
...connectionArgs,
},
resolve: (root, {names}) =>connectionFromArray(getUsers(names)),
},
但我收到了错误Cannot read property 'after' of undefined in implementing react-relay
在此先感谢。
答案 0 :(得分:6)
Relay目前仅支持三种类型的根字段(请参阅facebook/relay#112):
{ user { id } }
返回{"id": "123"}
{ post(id: "456") { id } }
返回{"id": "456"}
{ users(ids: ["123", "321"]) { id } }
返回[{"id": "123"}, {"id": "321"}]
解决方法是创建一个根域(通常称为viewer
),返回包含这些字段的节点。嵌套在Viewer
(或任何其他节点)内时,允许字段具有任何返回类型,包括列表或连接。当您在GraphQL服务器中包装此对象中的字段时,您可以像这样查询它们:
{
viewer {
users {
id,
fullName,
}
}
}
Viewer
类型是一种节点类型,由于它只有一个实例,因此id
应该是一个常量。您可以使用globalIdField
帮助程序定义id
字段,并添加要使用Relay查询的任何其他字段:
const viewerType = new GraphQLObjectType({
name: 'Viewer',
interfaces: [nodeInterface],
fields: {
id: globalIdField('Viewer', () => 'VIEWER_ID'),
users:{
type: new GraphQLList(userType),
resolve: (viewer) => getUsers(),
},
},
});
在客户端,您需要将路径中的根查询更改为{ viewer }
并在Viewer
上定义片段:
export default Relay.createContainer(UserList, {
fragments: {
viewer: () => Relay.QL`
fragment on Viewer {
users {
fullName,
local {
email,
},
images {
full,
},
currentPostCount,
isPremium,
}
}
`,
},
});