Hey guys, I'm learning graphql via graphcool, I'm ...
# prisma-whats-new
i
Hey guys, I'm learning graphql via graphcool, I'm trying to get the sum of all payments in my db. I saw that graphcool havn't aggregates operations for now. I'm trying to make a resolver but I can't understand how it can work for now; Have you any guide to help me with that ? (I know that I can make this operation client side, it's not the purpose)
e
The documentation suggests custom aggregations be precalculated in a function. I'm guessing "operationAfter" would achieve this for you. You'd calculate the value after each relevant mutation. To store the value I suggest extending your schema with a "meta" table. It could be modeled as key/value, or you could add columns for every aggregation and retain a history of the value.
i
I thought about an operationAfter, but there is no hook on a get query operation. I don't have to store this value. I just want to add it to the response of a allPayments
e
So you can extend the schema as shown here: https://blog.graph.cool/extend-your-graphcool-api-with-resolvers-ca0f0270bca7#b987 And here's an example:
Copy code
type aggregatePaymentsPayload {
  value: Int
  count: Int
}

extend type Query {
  aggregateAllPayments(): aggregatePaymentsPayload
}
Copy code
import { fromEvent, FunctionEvent } from 'graphcool-lib'

export default async event => {
  try {
    const graphcool = fromEvent(event)
    const api = graphcool.api('simple/v1')

    const { allPayments } = await api.request(`
      query AllPaymentsQuery {
        allPayments {
          amount
        }
      }
    `)

    // return a shape matching your payload type, "aggregatePaymentsPayload"
    return {
      sum: allPayments.reduce((sum, { amount }) => sum + amount, 0),
      count: allPayments.length
    }
    
  } catch (e) {
    console.log(e)
    return { error: e }
  }
}