2016-04-23 49 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" 
     } 
     ] 
    } 
    } 
} 
相關問題