javascript - GraphQL:更新数组

标签 javascript typescript graphql prisma

我在更新解析器中的数组时遇到了一些问题。我正在使用 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}
            }
        }
    })
}

问题:

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

感谢您阅读到目前为止。

最佳答案

能否请您分享公开突变解析器的代码?如果您忘记在突变解析器对象中包含 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 绑定(bind)调用将在它不存在的情况下抛出错误,我们不需要明确检查它。

关于javascript - GraphQL:更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51915695/

相关文章:

javascript - Bazel 自动生成 ts_library 的依赖项

typescript - TypeWriter - 过滤没有给定属性的类或属性

PHP Laravel GraphQL 查询声明不兼容问题

github - 如何使用 github graphQL 获取有关特定用户的信息?

javascript字符串替换特殊字符

java - 转换 JSON 结构

java - 收到新消息的开始,但上一条消息未完成

arrays - 如何使用 typescript 获取枚举的所有值?

graphql - 为什么Apollo Client下载:schema fail with "Error: Cannot find module ' graphql/validation/rules/UniqueTypeNames'"

javascript - 带有 application/xml+xhtml 内容类型的 Dojo