我有这个数据模型:
type Item {
id: ID! @unique
title: String!
description: String!
user: User!
pictures: [Picture]
basePrice: Int!
addons: [Addon]
}
我正在编写一个名为parsedItem的查询,它接受参数中的id并查找项目(使用Prisma生成的项目默认查询),如下所示:
const where = { id: args.id };
const item = await ctx.db.query.item({ where },
`{
id
title
...
我需要在前端展示一个计算的值:“dynamicPrice”,它依赖于商品所拥有的插件数量。 例如: 商品#1有3个插件,每个插件的价值为$5。这个计算出来的值应该是
dynamicPrice = basePrice + 3 * 5
插件关系可能会发生变化,因此我需要在前端发出每个请求时计算这一点。
我很想做这样的事情:
item.dynamicPrice = item.basePrice + (item.addons.length * 5)
我希望在解析器中返回项目,但这无法实现。这会导致出现错误:
"message": "Cannot query field \"dynamicPrice\" on type \"Item\"." (当我尝试从前端查询项目时)
这个错误消息让我想:我应该将dynamicPrice作为datamodel上的一个字段吗?然后我可以在查询解析器中填充这个字段吗?我知道我可以,但这是一个好的方法吗?
这只是一个例子,我需要为这个项目模型创建更多计算值。
对于这个简单用例,什么是最好的可扩展解决方案/解决方法?