How to group by Graphql query result
Asked Answered
G

1

8

I have a following GraphQL query

query {
  Result: querydata {
    name
    code
    description
  }
}

that returns me the following data

{
  "data": {
    "Result": [
      {
        "name": "Class1",
        "code": "ST1",
        "description": "Value"
      },
      {
        "name": "Class1",
        "code": "ST2",
        "description": "Value"
      },
      {
        "name": "Class2",
        "code": "FS1",
        "description": "Value"
      },
      {
        "name": "Class2",
        "code": "FS2",
        "description": "Value"
      }
    ]
  }
}

In this data, I have a name field that either be "Class1" or "Class2". I wan't to group this data in a way that I can have Class1 and Class2 data separated. Is there any way of doing this. I could have achieved this by running 2 separate queries by providing a name filter but lets say I don't have that option.

I want to transform the result as follow

{
  "data": {
    "Result": [
      "Class1": [
          {
            "code": "ST1",
            "description": "Value"
          },
          {
            "code": "ST2",
            "description": "Value"
          }
      ]

      "Class2": [
          {
            "code": "FS1",
            "description": "Value"
          },
          {
            "code": "FS2",
            "description": "Value"
          }
      ]
    ]
  }
}
Gahan answered 18/9, 2018 at 10:59 Comment(3)
Did you ever accomplish your goal? I'm trying to do something similar so I can use the data more easily in Grafana.Cistaceous
Yes, I managed that by transforming query type and associated class object. Similar approach suggested by @Austio as well.Gahan
In fact I have used both query type transformation at server side (API) and Clint side (Vuejs) filteration/grouping etc. with Underscore.js library. Depending on the given scenario, if data returned by the API required to be pre formatted or we can just return flat kind ov structure where client will do the formatting as needed.Gahan
S
2

What you are describing is something that should either happen on the client side or allow your query type to receive a name option that you use to return the propper class, then the query below would work for what you are needing assuming it was able to lookup the name of the querydata

query {
  Class1: querydata(name: "Class1") {
    code
    description
  }
  Class2: querydata(name: "Class2") {
    code
    description
  }
}
Summand answered 18/9, 2018 at 17:30 Comment(1)
Yes above query will only work either if I manipulate the context in query type or I allow name as a filter. I was wondering if there is any option of formatting the output result.Gahan

© 2022 - 2024 — McMap. All rights reserved.