2017-07-04 22 views
0

說GET變量我有以下幾點:阿波羅GraphQL服務器:在解析器,從幾個層次在我的解析器更高

Query: { 
    author: (root, args) => API.getAuthor(args.authorId), 
}, 
Author: { 
    book: (author, args) => API.getBook(author.id, args.bookId), 
}, 
Book: { 
    // Here, I can't get the author ID 
    chapter: (book, args) => API.getChapter(authorId???, book.id, args.chapterId), 
} 

我的問題是從上面的例子很清楚,我怎麼能訪問變量從幾個層次更高? 我希望能夠提出請求如下所示:

author(authorId: 1) { 
    id 
    book(bookId: 31) { 
    id 
    chapter(chapterId: 3) { 
     content 
    } 
    } 
} 

而我的連接器,以獲得特定章節還需要作者的ID。

+0

你不能,而這intented – whitep4nther

+0

不書有 'AUTHOR_ID' 字段? – whitep4nther

+0

@ whitep4nther哦,該死的太糟了,爲什麼?不,在我的現實生活中,書沒有author_id字段。 – Bertrand

回答

1

您無法訪問GraphQL中更高級別的變量。

這是打算:因爲Book實體也可以包含在其他對象中。現在,您有author { book { chapter } },但您也可以有library { book { chapter } },其中author字段不會出現在查詢中,從而使author.id變量不可訪問。

每個對象都負責用他自己的數據獲取他的領域,這使得整個事物可組合。

但是,您可以做的是擴展API.getBooks函數的響應,將author_id字段添加到返回的對象。這樣,您將可以在您的Book實體內訪問它:book.authorId

function myGetBook(authorId, bookId) { 
    return API.getBook(authorId, bookId) 
    .then(book => { 
     return Object.assign(
     {}, 
     theBook, 
     { authorId } 
    ); 
    }); 
} 

然後:

Author: { 
    book: (author, args) => myGetBook(author.id, args.bookId), 
}, 
Book: { 
    chapter: (book, args) => API.getChapter(book.authorId, book.id, args.chapterId), 
} 
+0

哦,是的,這的確可行。非常感謝! – Bertrand