2016-07-18 89 views
1

我對於Graphql的遊標和MongoDB遊標之間的關係應該是什麼感到困惑。GraphQL和MongoDB遊標

我目前正在研究創建對象(mongo文檔)並將其添加到現有連接(mongo集合)的突變。添加對象時,突變返回添加的邊緣。應該看起來像這樣:

{ 
    node, 
    cursor 
} 

雖然node是實際添加的文檔,但我對於應該作爲遊標返回的內容感到困惑。

這是我的突變:

const CreatePollMutation = mutationWithClientMutationId({ 
    name: 'CreatePoll', 

    inputFields: { 
    title: { 
     type: new GraphQLNonNull(GraphQLString), 
    }, 
    multi: { 
     type: GraphQLBoolean, 
    }, 
    options: { 
     type: new GraphQLNonNull(new GraphQLList(GraphQLString)), 
    }, 
    author: { 
     type: new GraphQLNonNull(GraphQLID), 
    }, 
    }, 

    outputFields: { 
    pollEdge: { 
     type: pollEdgeType, 
     resolve: (poll => (
     { 
      // cursorForObjectInConnection was used when I've tested using mock JSON data, 
      // this doesn't work now since db.getPolls() is async 
      cursor: cursorForObjectInConnection(db.getPolls(), poll), 
      node: poll, 
     } 
    )), 
    }, 
    }, 

    mutateAndGetPayload: ({ title, multi, options, author }) => { 
    const { id: authorId } = fromGlobalId(author); 
    return db.createPoll(title, options, authorId, multi); //promise 
    }, 

}); 

謝謝!

回答

1

對你來說可能有點晚了,但也許它會幫助別人絆倒這個問題。

只需從您的解決方法中返回承諾即可。然後,您可以使用實際的polls陣列創建光標。像這樣:

resolve: (poll => 
    return db.getPolls().then(polls => { 
     return { cursor: cursorForObjectInConnection(polls, poll), node: poll } 
    }) 
) 

但仔細,你pollpolls的對象,現在有不同的起源和不嚴格相等。由於cursorForObjectInConnection使用javascript的indexOf,您的光標可能會最終成爲null。爲了防止出現這種情況,您應該自己查找對象索引並使用offsetToCursor來構造光標,如here所述。