Graphql is great and I've started using it in my app. I have a page that displays summary information and I need graphql to return aggregate counts? Can this be done?
7 Answers
You would define a new GraphQL type that is an object that contains a list and a number. The number would be defined by a resolver function.
On your GraphQL server you can define the resolver function and as part of that, you would have to write the code that performs whatever calculations and queries are necessary to get the aggregate counts.
This is similar to how you would write an object serializer for a REST API or a custom REST API endpoint that runs whatever database queries are needed to calculate the aggregate counts.
GraphQL's strength is that it gives the frontend more power in determining what data specifically is returned. Some of what you write in GraphQL will be the same as what you would write for a REST API.
-
10Good explanation! I think the main takeaway point is that GraphQL doesn't do your calculations and aggregations for you. All of that is supposed to happen in the resolve function of the GraphQL query object, which needs to be told to retrieve the needed pre-aggregated data, does its work on it and then returns the result.– batjkoCommented Apr 13, 2016 at 15:11
There's no automatic aggregate function in GraphQL itself.
You can add a field called summary, and in the resolve function calculate the totals.
... need graphql to return aggregate counts? Can this be done?
Yes, it can be done.
Does GraphQL does it automatically for you? No, because it does not know / care about where you get your data source.
How? GraphQL does not dictate how you get / mutate the data that the user has queried. It's up to your implementation to get the requested aggregated data. You could get aggregated data directly from your MongoDB and serve it back, or you get all the data you need from your data source and do the aggregation yourself.
You should define a Type of aggregated data in Graphql and a function you want to implement it. For example, if you want to write the following query:
SELECT age, sum(score) from student group by age;
You should define the data type that you want to return:
type StudentScoreByAge{
age: Int
sumOfScore: Float
}
and a Graphql function:
getStudentScoreByAge : [StudentScoreByAge]
async function(){
const res = await client.query("SELECT age, sum(score) as sumOfScore
from Student group by age");
return res.rows;
}
If you are using Hasura, in the explorer, you can definitely see an "agregate" table name, thus, your query would look something similar to the following:
query queryTable {
table_name {
field1
field2
}
table_name_aggregate {
aggregate { count }
}
}
In your results, you will see the total row count for the query
"table_name_aggregate": {
"aggregate": {
"count": 9973
}
This depends on whether you build the aggregator into your schema and are able to resolve the field.
Can you share what kind of GraphQL Server you're running? As different languages have different implementations, as well as different services (like Hasura, 8base, and Prisma).
Also, when you say "counts", I'm imagining a count of objects in a relation. Such as:
query {
user(id: "1") {
name
summaries {
count
}
}
}
// returns
{
"data": {
"user": {
"name": "Steve",
"summaries": {
"count": 10
}
}
}
}
8base provides the count aggregate by default on relational queries.
If you come here because you're looking for a pagination for Supabase GraphQL, here's a summary for you:
- You can enable
totalCountin GraphQL by doing this:
COMMENT ON TABLE "articles" IS e'@graphql({"totalCount":{"enabled":true}})';
-- in this case articles is the table name, change with the one you like.
- You can use the totalCount, and cursor get pagination in GraphQL Supabase, summary is as follows:
Let say we have the following query
query {
eventsCollection(first: 2, offset: 0) {
totalCount
edges {
node {
id
title
}
}
pageInfo {
hasNextPage
hasPreviousPage
endCursor
}
}
}
Then you can get something like:
{
"data": {
"eventsCollection": {
"edges": [
{
"node": {
"id": "0031af3b-060e-4c9f-a6be-902e541ebfa7",
"title": "Faith in the Digital Age"
}
},
{
"node": {
"id": "89171815-302f-405a-ab54-6480bffc1f09",
"title": "Community Yoga Day"
}
}
],
"pageInfo": {
"endCursor": "WyI4OTE3MTgxNS0zMDJmLTQwNWEtYWI1NC02NDgwYmZmYzFmMDkiXQ==",
"hasNextPage": true,
"hasPreviousPage": false
},
"totalCount": 4
}
}
}
Using the end cursor WyI4OTE3MTgxNS0zMDJmLTQwNWEtYWI1NC02NDgwYmZmYzFmMDkiXQ== now you can call like this:
query {
eventsCollection(first: 2, offset: 0, after: "WyI4OTE3MTgxNS0zMDJmLTQwNWEtYWI1NC02NDgwYmZmYzFmMDkiXQ==") {
totalCount
edges {
node {
id
title
}
}
pageInfo {
hasNextPage
hasPreviousPage
endCursor
}
}
}
Then you can get response like this:
{
"data": {
"eventsCollection": {
"edges": [
{
"node": {
"id": "8e1e21d2-bd95-4f6b-beb2-0ef2c03f0499",
"title": "Citizens and Smart Cities"
}
},
{
"node": {
"id": "a62041cc-67a0-4aae-b4ac-ac58184186e2",
"title": "AI for Good Summit"
}
}
],
"pageInfo": {
"endCursor": "WyJhNjIwNDFjYy02N2EwLTRhYWUtYjRhYy1hYzU4MTg0MTg2ZTIiXQ==",
"hasNextPage": false,
"hasPreviousPage": true
},
"totalCount": 4
}
}
}
totalCount is used to calculate the number of pages.
For example, if you take 5 items per page using first: 5, and totalCount is 100, then it becomes 100/5 = 20 pages.
Later, you'll use offset: pageSize * pageNumber to set the page. So if the page size is 5 and you're on page 2, then the offset would be 10.
cmiiw