No one
No one

Reputation: 71

Return Graphql Count

I have this Graphql query

 "{TABLE_NAME{
    id
    severity
    des
    ip
    hostname
    description

  }
}"; 

That's return over 1000 records, how to do:

SELECT COUNT(*) FROM TABLE_NAME

in Graphql ?

Upvotes: 6

Views: 21290

Answers (3)

Metasal
Metasal

Reputation: 111

query {
  posts {
    meta {
      pagination {
        total
      }
    }
  }
}

where posts is the name of your collection

source = https://graphql.org/learn/pagination/

Upvotes: 1

Mamadou OUOLOGUEM
Mamadou OUOLOGUEM

Reputation: 27

you can easily use:

query {
    listOfElts (first: 1) { 
        totalCount 
    }
}

Upvotes: 0

vbranden
vbranden

Reputation: 5986

The short answer is you dont. A GraphQL object type does not necessarily map 1:1 to a database table so you cannot look at it that way. If you want to get a count from a table, you need to add that as either a field to your output type or as its own field. I assume since you want to find out how large a table is before you query it you want a 'tableInfo' type query which would look like

const TableInfo = new GraphQLObjectType({
  name: 'TableInfo',
  fields: {
    count: GraphQLInt
  }
})
const Query = new GraphQLObjectType({
  name: 'Query',
  fields: {
    tableInfo: {
      type: TableInfo,
      args: {
        name: new GraphQLNonNull(GraphQLString)
      },
      resolve (source, args) {
        return new Promise((resolve, reject) => {
          connection.query(
            'SELECT COUNT(*) from ' + args.name,
            (error, results) => {
              return error ? reject(error) : resolve(results)
            }
          )
        })
      }
    }
  }
})
const schema = new GraphQLSchema({
  query: Query
})

then request with

query Info {
  tableInfo(name: "my_table") {
    count
  }
}

that said, this is not a good pattern and if you are expecting a query to return a large amount of results you should instead use pagination. Best practices are here http://graphql.org/learn/pagination/

Upvotes: 3

Related Questions