Prisma graphql 计算域 [英] Prisma graphql computed fields
问题描述
我有这个数据模型:
type Item {
id: ID! @unique
title: String!
description: String!
user: User!
pictures: [Picture]
basePrice: Int!
addons: [Addon]
}
我正在编写一个名为 parsedItem 的查询,它从参数中获取 id 并查找 Item(使用由 Prisma 生成的 Item 的默认查询),如下所示:
I'm writing a query called parsedItem that takes the id from arguments and looks for the Item (using the default query for Item generated by Prisma), something like this:
const where = { id: args.id };
const item = await ctx.db.query.item({ where },
`{
id
title
...
我需要在前端显示一个计算值:dynamicPrice",它取决于项目拥有的插件数量.例如:Item #1 有 3 个插件,每个插件的价值为 5 美元.这个计算值应该是
I need to show on the frontend a computed value: "dynamicPrice" it depends on the quantity of the Addons that the Item has. e.g: Item #1 has 3 addons, each addons has a value of $5. This calculated value should be
dynamicPrice = basePrice + 3 * 5
插件关系可能会改变,所以我需要在前端发出的每个请求中计算这个.
The Addon relation could change, so I need to compute this in every request the frontend makes.
我非常想做这样的事情:
I'd like so much to do something like:
item.dynamicPrice = item.basePrice + (item.addons.length * 5)
并在解析器中返回这个项目,但这不起作用.抛出一个错误:
and return this item in the resolver, but this doesn't work. That throw an error:
"message": "无法在类型 \"Item\" 上查询字段 \"dynamicPrice\"."(当我尝试从前端查询项目时)
"message": "Cannot query field \"dynamicPrice\" on type \"Item\"." (when I try to query the Item from the frontend)
这个错误信息让我思考:我应该创建 dynamicPrice 作为数据模型上的一个字段吗?然后我可以在查询解析器中填充这个字段吗?我知道我可以,但这是一个好方法吗?
This error message makes me think: Should I create dynamicPrice as a field on the datamodel? Can I then populate this field in the query resolver? I know I can, but is this a good approach?
这是一个例子,我需要为这个 Item 模型创建更多的计算值.
This is an example, I need to create more computed values for this Item model.
对于这个简单的用例来说,最好的可扩展解决方案是什么?
推荐答案
您需要为 Item
类型的 dynamicPrice
字段创建字段解析器.它看起来像这样:
You need create field resolver for dynamicPrice
field at Item
type. It will looks like that:
const resolvers = {
Query: {
parsedItem: (parent, args, ctx, info) => {
...
}
...
},
Item: {
dynamicPrice: parent => parent.basePrice + parent.addons.length * 5
}
}
您可以在指南中找到更多详细信息到常见的解析器模式.
这篇关于Prisma graphql 计算域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!