2017-07-04 17 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