我在更新解析器中的数组时遇到了一些问题。我正在使用 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
作为响应。
除此之外,我在代码中发现了另一个问题。由于您在 Service
和 Comment
之间有关系,您可以使用单一突变来创建评论并将其添加到服务中。您不需要编写两个单独的突变来实现这一点。您的解析器可以更改为如下所示:
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/