2016-04-23 58 views
2

我开始使用GraphQL。我正在尝试将数据解析为GraphQL类型。我不明白为什么以下不起作用。如何正确使用GraphQLList和GraphQLInterfaceType?

鉴于这样的数据:

{ 
    "kind": "youtube#searchListResponse", 
    "etag": "\"CuSCwMPVmgi8taDtE2LV6HdgkN0/USvbH1nSht52L3y8EP6BIwVRhgM\"", 
    "items": [{ 
     "kind": "youtube#searchResult", 
     "etag": "\"CuSCwMPVmgi8taDtE2LV6HdgkN0/xpywjUARlQ0Ai4IucTvXRNCfTcE\"", 
     "id": { 
      "kind": "youtube#video", 
      "videoId": "zvRbU1Ql5BQ" 
     } 
    }] 
} 

这是代码把它打出来。

const ItemType = new GraphQLInterfaceType({ 
    name: 'Item', 
    fields: { 
    kind: { type: StringType }, 
    }, 
}); 

const YoutubeDataType = new GraphQLObjectType({ 
    name: 'PublicYoutube', 
    fields: { 
    kind: { type: new GraphQLNonNull(StringType) }, 
    etag: { type: new GraphQLNonNull(StringType) }, 
     items: { type: new GraphQLList(ItemType) }, // returns null 
    // items: { type: StringType }, // returns "[object Object]"... so it's being passed in 
    }, 
}); 

这是通过GraphiQL返回的内容。为什么items等于null

{ 
    "data": { 
    "publicyoutube": { 
     "kind": "youtube#searchListResponse", 
     "etag": "\"CuSCwMPVmgi8taDtE2LV6HdgkN0/OspGzY61uG9sSD_AWlfwkTBjG-8\"", 
     "items": [ 
     null 
     ] 
    } 
    }, 
    "errors": [ 
    { 
     "message": "Cannot read property 'length' of undefined" 
    } 
    ] 
} 

谢谢你的帮助。

回答

3

我误解了GraphQLInterfaceType的用途,并且使用了错误的方法。而不是使用GraphQLInterfaceType,它应该是GraphQLObjectType;

const ItemType = new GraphQLObjectType({ 
    name: 'Item', 
    fields: { 
    kind: { type: StringType }, 
    }, 
}); 

const YoutubeDataType = new GraphQLObjectType({ 
    name: 'PublicYoutube', 
    fields: { 
    kind: { type: new GraphQLNonNull(StringType) }, 
    etag: { type: new GraphQLNonNull(StringType) }, 
     items: { type: new GraphQLList(ItemType) }, // returns null 
    // items: { type: StringType }, // returns "[object Object]"... so it's being passed in 
    }, 
}); 

输出:

{ 
    "data": { 
    "publicyoutube": { 
     "kind": "youtube#searchListResponse", 
     "etag": "\"CuSCwMPVmgi8taDtE2LV6HdgkN0/-aZNXBVLYOJwPMdleXmbTlJSo_E\"", 
     "items": [ 
     { 
      "kind": "youtube#searchResult" 
     } 
     ] 
    } 
    } 
}