Sel*_*bou 5 javascript typescript graphql prisma
我在更新解析器中的数组时遇到了一些问题。我正在用typescript.
我在datamodel.graphqlfor 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!
}
Run Code Online (Sandbox Code Playgroud)
在Prisma连接到GraphQl服务器,并在这其中,我所定义的突变:
commentService(id: String!, comment: String!): Service!
Run Code Online (Sandbox Code Playgroud)
所以是时候为给定的突变实现解析器了,我正在这样做:
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}
}
}
})
}
Run Code Online (Sandbox Code Playgroud)
我在查询操场时收到的唯一信息null不是我给出的评论。
感谢您阅读到目前为止。
您能否分享公开突变解析器的代码?null如果您忘记在突变解析器对象中包含解析器,您可能会收到响应commentService。
除此之外,我在代码中还发现了一个问题。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}
}
}
}
}
})
}
Run Code Online (Sandbox Code Playgroud)
请注意,我还删除了在执行更新之前检查服务是否存在的查询。原因是,如果 updateService 绑定调用不存在,则它会抛出错误,我们不需要显式检查。
| 归档时间: |
|
| 查看次数: |
2469 次 |
| 最近记录: |