viewer 不是 Relay 特有的。这只是一个字段名称。你是对的。该字段通常代表应用程序的用户或查看者的 GraphQLObject 类型。
根查询类型是我们在模式对象中定义并作为query 传递的GraphQL 对象。例如,在todo example application 中,它是Root。
export const schema = new GraphQLSchema({
query: Root,
mutation: Mutation,
});
在relay-treasurehunt example application中,根查询类型为queryType。
export const schema = new GraphQLSchema({
query: queryType,
mutation: mutationType,
});
根查询类型是访问其他数据的主要访问点。这些其他数据被列为根查询对象的字段。与任何 GraphQL 对象一样,根查询类型可以有一个或多个字段。在 todo 示例应用程序中,它有一个名为 viewer 的字段:
const Root = new GraphQLObjectType({
name: 'Root',
fields: {
viewer: {
type: GraphQLUser,
resolve: () => getViewer(),
},
node: nodeField,
},
});
在relay-treasurehunt 示例应用程序中,根查询类型有一个名为game 的字段。
const queryType = new GraphQLObjectType({
name: 'Query',
fields: () => ({
node: nodeField,
game: {
type: gameType,
resolve: () => getGame(),
},
}),
});
现在如果有一个viewer 字段来代表应用程序用户或网站查看者,那么用户是匿名还是登录完全取决于应用程序。如果用户需要登录,可以实现登录的突变。您还可以限制对数据的访问。 Jonas Helfer 发布了 excellent answer 以说明如何在服务器端进行用户访问检查。