【问题标题】:GraphQL & MongoDB cursorsGraphQL 和 MongoDB 游标
【发布时间】:2016-11-21 12:49:57
【问题描述】:

我对 GraphQL 的游标和 MongoDB 的游标之间应该是什么关系感到困惑。

我目前正在研究创建对象(mongo 文档)并将其添加到现有连接(mongo 集合)的突变。添加对象时,突变返回添加的边缘。应该是这样的:

{
  node,
  cursor
}

虽然节点是实际添加的文档,但我对应该作为光标返回的内容感到困惑。

这是我的突变:

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
  },

});

谢谢!

【问题讨论】:

    标签: mongodb graphql relayjs graphql-js


    【解决方案1】:

    对你来说可能有点晚了,但也许它会帮助其他人遇到这个问题。

    只需从您的 resolve 方法返回一个承诺。然后,您可以使用实际的 polls 数组创建光标。像这样:

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

    但要小心,你的pollpolls 中的对象现在有不同的起源,并不严格相等。由于cursorForObjectInConnection 使用javascript 的indexOf,您的光标可能最终会变成null。为了防止这种情况,您应该自己找到对象索引并使用offsetToCursor 来构造您的游标,如here 所述。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-20
      • 2012-12-11
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 2020-12-14
      • 2018-08-25
      • 2018-08-25
      相关资源
      最近更新 更多