如何将对象列表连接到Relay的节点
在GraphQL中,我有以下结构
# represents any node with GlobalIdField node(id: "uniqueIdOfNode") { } # represents actually logged user viewer { }
在示例MVC应用程序模式待办事项连接到查看器,所以当查询你只能得到属于login用户的待办事项。
但是,在我的情况下,我想要显示与用户无关的数据。 假设数据是types国家这是NodeInterfaceType,我想问一个查询国家的名单。 所以在Relay中,我可以在CountryList中创build一个片段,并使用Relay将其传递给React组件。
如果我写的不够清楚,就让我知道,因为我很困惑,而且我不确定我是否解释得好。
我用PHP编写了GraphQL服务器,但代码或提示可以用node.js编写,我也会理解它。
怎么做?
更新
一些代码:
schema.graphql
# A country type Country implements NodeInterface { # The ID of an object id: ID! countryId: Int phonePrefix: String name: String timezone: String } # Representation of date and time in "Ymd H:i:s" format scalar DateTime interface NodeInterface { # The ID of an object id: ID! } type Query { # Fetches an object given its ID node( # The ID of an object id: ID! ): NodeInterface viewer: User countries: [Country] } type User implements NodeInterface { # The ID of an object id: ID! username: String userId: Int lastLoginDateTime: DateTime }
SampleRoute.js – 用作打开React应用程序的第一条路线
import Relay from 'react-relay'; export default class extends Relay.Route { static queries = { countries: () => Relay.QL` query AppHomeRoute { viewer } `, }; static routeName = 'AppHomeRoute'; }
App.js我想在Index组件中有国家列表,理想情况下在App js中,我不希望事件通过带有道具的国家,但是我希望它们在Index组件中,将来会重命名为CountryList
import React, { Component } from 'react'; import Relay from 'react-relay'; import Index from './page/index'; import './App.css'; class App extends Component { render() { console.log(this.props); return ( <Index country={this.props.countries} /> ); } } export default Relay.createContainer(App, { fragments: { countries: () => Relay.QL` countries { ${Index.getFragment('country')} } } // fragment F1 on Country { // ${Index.getFragment('country')} // }, ` } });
现在我得到一个错误:
SampleRoute.js:5未捕获错误:GraphQLvalidation错误“无法查询字段”查看器“types”查询“
我完全不明白,因为当我用graphiql查询服务器,那么它工作正常。
查询:
{ viewer { id username } node(id:"dXNlcjo2NjY=") { id username } countries { name } }
响应:
{ "data": { "viewer": { "id": "dXNlcjo2NjY=", "username": "Robert" }, "node": { "id": "dXNlcjo2NjY=", "username": "Robert" }, "countries": [ { "name": "AFGHANISTAN" }, { "name": "ALBANIA" }, (...) ] } }