Count with GraphQL

This guide explains how to count data with a GraphQL query.

The count aggregation currently has some issues and this feature is also not available for Bookshelf (SQL databases).

With this guide we will code our own count query.

Here is the GraphQL documentation which we will use to achieve our goal.

Setup the application

In this example, we will use a Restaurant API.

Make sure you have a Content Type with some entries.

Create schema.graphql file

To be able to add a new custom query (or mutation), we will have to create a schema.graphql.js file in your Restaurant API.

Path./api/restaurant/config/schema.graphql.js

  1. module.exports = {
  2. query: ``,
  3. resolver: {
  4. Query: {},
  5. },
  6. };

Create count query

The count query will call the count service function of the Restaurant API.

It needs a JSON object as params, so we will add a where options in the GraphQL query.

Path./api/restaurant/config/schema.graphql.js

  1. module.exports = {
  2. query: `
  3. restaurantsCount(where: JSON): Int!
  4. `,
  5. resolver: {
  6. Query: {
  7. restaurantsCount: {
  8. description: 'Return the count of restaurants',
  9. resolverOf: 'application::restaurant.restaurant.count',
  10. resolver: async (obj, options, ctx) => {
  11. return await strapi.api.restaurant.services.restaurant.count(options.where || {});
  12. },
  13. },
  14. },
  15. },
  16. };

And tada, you can now request the count of your Content Type.

Query example

  • Count all restaurants
  1. {
  2. restaurantsCount
  3. }
  • Count all restaurants that have _3rd as district value.

Based on the FoodAdvisorCount with GraphQL - 图1 (opens new window) restraurant model.

  1. {
  2. restaurantsCount(where: { district: "_3rd" })
  3. }