Simplifying GraphQL Queries for HTTP Caching

The Problem with GraphQL Syntax

The issue lies in the GraphQL syntax itself. The nesting behavior of fields in a GraphQL query makes it difficult to read and write in a single line. This is because the nesting can advance and retreat throughout the query, making it hard to grasp when written in a single line.

Designing an Alternative Syntax

To overcome this challenge, an alternative syntax called PQL (PoP Query Language) has been designed. PQL ensures that the query flow is always forward, eliminating the need for retreating nested fields. This makes it possible to write queries in a single line that are easy to read and understand.

Key Features of PQL

  • Fields with aliases: Written with the alias after the field name, making it a natural flow.
  • Directives: Identified with a surrounding syntax <...>, allowing for nested directives.
  • Field separation: Fields are separated using the | character, making it easy to compose queries.
  • Connections: Defined using the . character, which always advances the query.
  • Bookmarks: Can be used to remove verbosity and provide shortcuts to already-traversed paths.

Making Queries Visually Appealing

PQL allows for line breaks and spaces to be added to the query, making it easier to visualize and understand. The query can be copied and pasted into the browser’s address bar, and all line breaks will be automatically removed, creating the equivalent single-line query.

query {
  user(id: 1) {
    name
    | email
    
  }
}

Accepting Only Advancing Fields

PQL uses the , character to join elements, allowing the query to start again from the root. This ensures that the query always advances, never retreats.

query {
  user(id: 1), 
  user(id: 2) {
    name
    | email
  }
}

Simplifying Field Arguments

PQL omits string quotes when composing the query, making it easier to write. Additionally, field arguments can be made implicit when the field has only one argument.

query {
  user(id: 1) {
    name
    | email(address: "[email protected]")
  }
}

Variables and Fragments

PQL uses HTTP standard inputs to pass variables via $_GET or $_POST. Fragments are defined as inputs in $_GET or $_POST and are referenced with --.

query {
  user(id: $_GET["id"]) {
    name
    | email
    --fragment
  }
}

Converting Queries between GraphQL and PQL

PQL is a superset of the GraphQL query syntax, making it possible to convert queries between the two. However, not every query written in PQL can be written using the GraphQL syntax due to PQL’s additional features.

query {
  user(id: 1) {
    name
    email
  }
}
query {
  user(id: 1) {
    name
    | email
  }
}

Leave a Reply