Phil Zona Dot Net

GraphQL first impressions

When it comes to blogging, I'm a huge fan of Ghost. I run a couple sites on it and it's awesome. But I'm even more a fan of new technology, so lately I've been playing with GatsbyJS, a static site generator that uses React.

React is fun to use and I plan to write more on it, but Gatsby's killer feature is GraphQL.

GraphQL is a query language I haven't used before and, honestly, seemed a little too hip for me to get into. But now that I've tried it, I want to rewrite every project I've ever made. It's so, so simple and surprisingly fast.

Compare this:

SELECT Actors, ReleaseYear
FROM Movies
WHERE Title="The Matrix";

to this:

{
    movie(title: 'The Matrix') {
        actors
        releaseYear
    }
}

Okay, there's not much difference in complexity for simple queries. I'm not a SQL hater. But I am a JSON lover, and that's a big reason GraphQL has me so hyped up. Notice that the GraphQL query looks like data. Now, check out the response:

{
    "data": {
        "movie": {
            "The Matrix": {
                "releaseYear": "1999",
                "actors": [
                    "Keanu Reeves",
                    "Laurence Fishburne"
                ]
            }
        }
    }
}

Look familiar? Identical even? That's because it is. GraphQL is easy to read because the response is in the same format as the request. You ask for certain fields, and those fields are what you get. Nothing more, nothing less.

This simplicity also makes GraphQL super easy to develop with. It's predictable and, if you're working with JSON, simple to imagine the format of the response when you're planning how to handle it. You can literally map your request to your response 1:1.

There's also the removal of database overhead. I said before I'm not a SQL hater, and I'm really not, but database administration is something I have zero passion for, and frankly, I just don't like anything that doesn't look similar to the code I'm already writing. SQL isn't all that attractive to begin with, but it sticks out like a sore thumb in JavaScript. MongoDB is fine, but you still have to manage the DB (I'll get into Mongo security some other time).

My favorite thing about GraphQL is how simple it is as a whole. You determine the data structure, but also how it's stored. With plugins, you can even query the filesystem for Markdown files, which is an amazing feature to have with static site generators like Gatsby.

It isn't perfect, of course. I imagine migrating from something like SQL would be a nightmare, and I've yet to get deep into the server-side. But if GraphQL is half as good as it seems, then at the very least I'll get to make few more projects with weird parts that not everyone knows about. And that's as good a reason as I can think of.