Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prisma graphql computed fields

I have this datamodel:

type Item {
  id: ID! @unique
  title: String!
  description: String!
  user: User!
  pictures: [Picture]
  basePrice: Int!
  addons: [Addon]
}

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
      ...

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": "Cannot query field \"dynamicPrice\" on type \"Item\"." (when I try to query the Item from the frontend)

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?

This is an example, I need to create more computed values for this Item model.

What is the best scalable solution/workaround for this simple use case?

like image 756
Adrián E. Avatar asked Mar 15 '26 11:03

Adrián E.


1 Answers

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
  }
}

More details you can find at A Guide to Common Resolver Patterns.

like image 176
galkin Avatar answered Mar 18 '26 01:03

galkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!