【问题标题】:GraphQL: Updating an arrayGraphQL:更新数组
【发布时间】:2019-01-25 16:40:52
【问题描述】:

我在更新解析器中的数组时遇到了一些问题。我正在使用typescript 构建。

说明

我在datamodel.graphql 中有Prisma

type Service @model {
    id: ID! @unique
    title: String
    content: String
    createdAt: DateTime!
    updatedAt: DateTime!
    comments: [Comment!]! // Line to be seen here
    author: User!
    offer: Offer
    isPublished: Boolean! @default(value: "false")
    type: [ServiceType!]!
}

type Comment @model {
    id: ID! @unique
    author: User! @relation(name: "WRITER")
    service: Service!
    message: String!
}

Prisma 连接到GraphQl 服务器,在这个服务器中,我定义了突变:

commentService(id: String!, comment: String!): Service!

现在是为给定突变实现解析器的时候了,我正在这样做:

async commentService(parent, {id, comment}, ctx: Context, info) {
    const userId = getUserId(ctx);
    const service = await ctx.db.query.service({
        where: {id}
    });
    if (!service) {
        throw new Error(`Service not found or you're not the author`)
    }

    const userComment = await ctx.db.mutation.createComment({
        data: {
            message: comment,
            service: {
                connect: {id}
            },
            author: {
                connect: {id:userId}
            },
        }
    });

    return ctx.db.mutation.updateService({
        where: {id},
        data: {
            comments: {
               connect: {id: userComment.id}
            }
        }
    })
}

问题:

查询游乐场时我收到的唯一信息是null,而不是我给出的评论。

感谢您到目前为止的阅读。

【问题讨论】:

    标签: javascript typescript graphql prisma


    【解决方案1】:

    如果我正确理解了这个问题,您将其称为 commentService 突变,结果您得到 null?按照您的逻辑,您应该得到 ctx.db.mutation.updateService 解析的任何内容,对吗?如果您希望它确实是一个Service 对象,那么您可能无法取回它的唯一原因是缺少await。你可能需要写return await ctx.db.mutation.updateService({ ...

    【讨论】:

      【解决方案2】:

      您能否分享您公开突变解析器的代码?如果您忘记在突变解析器对象中包含 commentService 解析器,您可能会收到 null 响应。

      除此之外,我在代码中还发现了一个问题。由于您在ServiceComment 之间有关系,因此您可以使用单一突变来创建评论并将其添加到服务中。您不需要编写两个单独的突变来实现这一点。您的解析器可以更改为如下所示的简单:

      async commentService(parent, {id, comment}, ctx: Context, info) {
          const userId = getUserId(ctx);
      
          return ctx.db.mutation.updateService({
              where: {id},
              data: {
                  comments: {
                     create: {
                         message: comment,
                         author: {
                            connect: {id:userId}
                         }
                     }
                  }
              }
          })
      }
      

      请注意,我还删除了查询以在执行更新之前检查服务是否存在。原因是,updateService 绑定调用会在它不存在的情况下抛出错误,我们不需要显式检查。

      【讨论】:

        猜你喜欢
        • 2017-06-30
        • 2018-06-07
        • 2020-09-27
        • 2021-12-02
        • 2019-04-17
        • 2016-10-20
        • 2018-04-30
        • 1970-01-01
        • 2020-05-30
        相关资源
        最近更新 更多