2016-09-22 39 views
6

如何使用新的GraphQL Schema語言爲我的friendList製作解析器? friendList有一組人_id。新的GraphQL的嵌套查詢buildSchema

我新,人型與GraphQL模式語言:

const schema = buildSchema(` 
 
    type People { 
 
    _id: String 
 
    firstName: String 
 
    lastName: String 
 
    demo: String 
 
    friendList: [People] 
 
    } 
 
    type Query { 
 
    getPeople(_id: String): People 
 
    } 
 
`);

我的老人們輸入與GraphQLObjectType:

const PeopleType = new GraphQLObjectType({ 
 
    name: 'People', 
 
    fields:() => ({ 
 
    _id: { 
 
     type: GraphQLString, 
 
    }, 
 
    firstName: { 
 
     type: GraphQLString, 
 
    }, 
 
    lastName: { 
 
     type: GraphQLString, 
 
    }, 
 
    friendList: { 
 
     type: new GraphQLList(PeopleType), 
 
     // pass @friends parentValue 
 
     resolve: ({ friends }) { 
 
     return People.find({ _id: { $in: friends } }).then(res => res); 
 
    }, 
 
    }), 
 
});

我想要實現這個查詢:

{ 
    people(_id: "ABC123") { 
    firstName 
    lastName 
    friendList { 
     firstName 
     lastName 
    } 
    } 
+0

你有沒有找到答案?現在正在努力克服這一點。 –

回答

3

我找不到用graphql-js做到這一點的一種方法,所以我切換到Apollo中稱爲graphql-tools的類似實現。

http://dev.apollodata.com/tools/graphql-tools/generate-schema.html

他們有一個叫做makeExecutableSchema函數,它寫在GraphQL模式語言的模式,並與(嵌套)解析器功能結合它。這解決了這個問題,如果你的代碼使用GraphQL Schema語言,它實際上很容易集成。

他們也有露出這種新的模式,它取代快車graphql,其GraphQL服務器另一個無關的工具:

http://dev.apollodata.com/tools/graphql-server/index.html

退房的文檔,希望這使您可以靈活地編寫複雜的代碼使用GraphQL Schema語言語法!

5

解析器應該返回一個類的新實例,如更新的GraphQL文檔中所述:http://graphql.org/graphql-js/object-types/

class People { 
    friendList() {} 
} 
var rootValue = { 
    getPeople: function() { 
    return new People(); 
    } 
} 
+0

好的一個快速的問題..如果friendlist是另一種類型,如(朋友)friendList:朋友。你如何在人員課堂上解決這個問題。 – kweku360

+0

@ kweku360'friendList'表示一個字段解析器。我鼓勵你檢查[contextable.js](https://github.com/xpepermint/contextablejs#graphql-root-resolver)。它現在可以用作GraphQL rootValue解析器。 – xpepermint