/

graphql2chartjs: Realtime charts made easy with GraphQL and ChartJS

Use GraphQL as a data source to build realtime charts with ChartJS

Example realtime chart

We started using ChartJS with GraphQL so that we could leverage GraphQL's realtime subscriptions to build realtime charts. Soon enough we realised that we can automate this process of restructuring the GraphQL data to a form that ChartJS expects.

graphql2chartjs is an open source tool that reshapes your GraphQL data as per the ChartJS API. This makes building charts as easy as simply making a GraphQL query.

The idea behind this tool is to generate ChartJS compliant data object from your GraphQL response by simply adding a few aliases in your GraphQL query.

Usage with Hasura

Hasura gives you an instant realtime GraphQL API on an existing Postgres database. You can create views to capture analytics and aggregations on your database and instantly turn them into charts.

If you're using Postgres and Hasura, this is what using graphql2chartjs looks like:

graphql2chartjs usage

Watch this video below to see a demo/tutorial of using Hasura with an existing Postgres database, creating views and building charts.

Sample client code

When using React,  Apollo and react-chartjs-2 on the client, your code for a realtime chart would look something like:

import {Subscription} from 'react-apollo';
import gql from 'graphql-tag';
import graphql2chartjs from 'graphql2chartjs';
import {Bar} from 'react-chartjs-2';

const Chart = () => (
  <Subscription
    subscription={gql`
      subscription {
        Articles: articleStats {
          label: title
          data: num_likes
        }
      }`}
    }>
    {({data} => {
      if (data) {
        const g2c = new graphql2chartjs(data, 'bar');
        return (<Bar data={g2c.data} />);
      }
      return null;
    }
  </Subscription>
);

Mapping GraphQL queries to ChartJS charts

Different types of charts need different structures in their datasets.

For example a bar chart dataset needs labels and data associated for each label; the ChartJS API refers to this as labeland data. Once you alias fields in your graphql query to label and data, and pass the response through graphql2chartjs, your dataset is ready to be used by bar chart in chartjs.

Bar / Line / Doughnut / Pie / Radar / Polar Area / Area

Charts of this type need 2 data inputs, label and data.

query {
	ArticleLikes : articles {     
		label: title
		data: likes
	}
}

Scatter / Bubble

Charts of this type need 2 data inputs: data_x, data_y (and data_r for bubble).

query {
	ArticleLikesVsComments : articles {
		data_x: num_likes
		data_y: num_comments
	}
}

Time series (line / bar)

Charts of this type need 2 data inputs, data_x or data_t and data_y. Note that there is no label.

query {
	StockPrices : stockprice {
		data_t: created
		data_y: price
	}
}

graphql2chartjs usage workflow

graphql2chartjs works in 3 steps:

  1. Initialise graphql2chartjs: const g2c = new graphql2chartjs()
  2. Add data from your graphql response: g2c.add(graphqlResponse.data, 'bar')
  3. Set your chart data to the data properly of the graphql2chartjs instance: g2c.data
  4. (Optional) Incrementally add data to the existing g2c instance: g2c.add(graphqlResponse.data, 'bar')

The add() function can also take a transformer function as the second argument. This transformation function can be used to  add custom properties to your data points from the GraphQL response. graphql2chartjs maps your GraphQL response with this transformer function and adds the given properties to the existing data points before performing any restructuring.  For example, if you wish to add different background colours for different data-sets, you would do something like:

g2c.add(graphqlResponse, (datasetName, dataPoint) => {
	if (datasetName === 'ArticleLikes') {
		return {
			chartType: 'bar',
			backgroundColor: 'red'
		}
	}
	return {
		chartType: 'bar',
		backgroundColor: 'bar'
	}
});

Whenever you are using a transformer function, the property chartType is mandatory because graphql2chartjs must know how it should add the given properties in the ChartJS data.

Read more detailed examples and instructions in the readme.


Take it for a spin

Do try graphql2chartjs and let us know what you think :) Refer to the Hasura docs if you’re looking for things like setting up security/access control on your GraphQL API.

We hang on discord, on github and our website intercom. Feel free to ask us questions :)

Blog
15 Mar, 2019
Email
Subscribe to stay up-to-date on all things Hasura. One newsletter, once a month.
Loading...
v3-pattern
Accelerate development and data access with radically reduced complexity.