2
votes

I'm trying to figure out if this is even possible and if there is a best practice for this to accomplish. We're implementing a GraphQL API into Laravel using the package https://github.com/Folkloreatelier/laravel-graphql

Let's say we want all cars grouped by brand to show the amount per brand in a graph.

A request without grouping should look something like this:

{
  cars {
    id,
    brand
  }
}

This way the amount per brand can be calculated at client side. But how to do this at server side.

For example:

{
  carMetrics(groupBy: "brand") {
    group,
    amount
  }
}

This will return an array of objects containing the group and amount of cars within that group.

Because the definition of the args and result is final we've got to create a new query and type for every object which needs to be grouped. Is this the way to go or is there a more dynamic way to implement the group by in GraphQL?

1

1 Answers

1
votes

I setup a quick example of an approach I might take to something like this over on Apollo Launch pad: https://launchpad.graphql.com/w9740qm8wz. You can use the query at the bottom to test it out (it doesn't save that for you).

The definitions would like like this

type Car {
  id: ID
    manufacturer: String
    name: String
}

type Manufacturers {
    name: String
    cars: [Car]
}

type Query {
  cars: [Car]
  manufacturers: [Manufacturers]
}

And the queries would look more like this:

{
  cars {
    ...car
  }
  manufacturers {
    name
    cars{
      ...car
    }
  }
}

fragment car on Car {
    id
    manufacturer
    name
}