Prisma graphql计算字段 [英] Prisma graphql computed fields

查看:90
本文介绍了Prisma graphql计算字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数据模型:

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

Addon关系可能会改变,因此我需要在前端发出的每个请求中都对此进行计算.

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 \.(当我尝试从前端查询商品时)

此错误消息使我想到:是否应该将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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆