The Minimalist Magician's guide on how to format GraphQL queries using Prettier

Thankfully, there's no need to resort to pentagrams and the dark arts. Here's how to get Prettier to auto-format GraphQL queries.

const query = /* GraphQL */ {
  query getPages {
    allPages {
      title
    }
  }
}

This is it, thanks to comment tags. Big shout out to Jayden Seric who listed out various ways to trick syntax highlighters and formatters into doing the right thing. Comment tags lets Prettier correctly find and format strings containing GraphQL queries.

How to format and import GraphQL files

It's easier to coax Prettier into formatting .graphql or .gql files. But then there's the business of importing these queries into your code. So, for importing these files I recommend using Webpack's raw-loader.

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.(gql|graphql)$/i,
        use: 'raw-loader',
      },
    ],
  },
};

This Webpack configuration will not offer you advanced GraphQL features that other, more specialized libraries might provide. However, you should ask yourself what exactly are those features you'll be missing? For instance, GraphQL Fragments are still supported with this raw-loader approach.

Here's an extended example of importing a query and querying. For the actual data fetching I use a plain fetch call.

import getPagesQuery from './getPagesQuery.gql'

const getData = async() => {
  const variables = {
    userId: '123'
  }
  const { data, errors = [] } = await fetch('example.org/graphql', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      query: getPagesQuery,
      variables
    })
  })
  .then(res => res.json())
  .catch(err => console.log('fetch() failed', err))

  if (errors.length > 0) {
    console.log(`GraphQL call errored with:`, JSON.stringify(errors, null, 2))
    throw new Error('GraphQL query failed, better check the logs.')
  }

  return data
}

A note on GraphQL by venture capitalists

To close things off, I want to highlight that a lot of venture capital is currently being poured into GraphQL-based startups. Many startups offer open-source packages that just happen to work well with their closed-source offerings. There's nothing wrong with this open-core approach to open source, but I want avoid vendor lock-in where possible.

What GraphQL solves really well: Is enabling API consumers to effectively explore, and traverse node-based graphs of data (tree-structures) and be explicit about exactly what data they want in return. This is something I've certainly struggled with in classic REST approaches, which I detailed here.

Perhaps to the dismay of GraphQL-based startups, I hope this article shows that there's no need to download a universe packages to work effectively with GraphQL. If you still want to make use of more GraphQL-specific packages you should stop to consider exactly what you get in return for the added complexity.

See also

  • $ gem uninstall hairball. This is a post I wrote about my first-hand experience of buying into and being burnt by complexity.
  • Keynote: Simplicity Matters by Rich Hickey. This is a great, evergreen talk on complexity that I think offers valuable lessons for all programmers. This talk is not a silver bullet to ward you against complexity but it will make it easier to reason about it.