Compress GraphQL Query?

Viewed 1252

I am looking for a standard way of compressing a GraphQL query/response to send it through MQTT.

I am thinking of something that can:

  • Remove extra spaces
  • Remove extra new lines (\n, \r);
  • Compress the message (zlib?)

I took a look to Graphene and other GraphQL modules for Python, but I have not found what I am looking for yet.

Is there a terminology that I am missing or is this something that I should not do?

1 Answers

The simplest way to compress a GraphQL query in Python I could come up with is:

import shlex

query_with_strings = """
        query someQuery    {
                Field(
                 search: "string with   spaces"
                ) {
                        foo
                }
        }
"""


def compress_graphql(q):
    """Compress a GraphQL query by removing unnecessary whitespace.

    >>> compress_graphql(query_with_strings)
    u'query someQuery { Field( search: "string with   spaces" ) { foo } }'
    """
    return u' '.join(shlex.split(q, posix=False))

This assumes that all queries are already unicode (Python 2) or str (Python 3) objects.

Running the doctest will pass.

Related