đŸ› ïžToolsShed

GraphQL Query Formatter

Format and beautify GraphQL queries, mutations, subscriptions, and fragments with proper indentation.

Questions Fréquentes

Implémentation du Code

def format_graphql(query: str, indent: int = 2) -> str:
    """Simple GraphQL formatter."""
    result = []
    depth = 0
    pad = " " * indent
    i = 0
    q = query.strip()

    while i < len(q):
        ch = q[i]
        if ch == '"':
            # Consume string
            j = i + 1
            while j < len(q):
                if q[j] == "\\" and j + 1 < len(q):
                    j += 2
                    continue
                if q[j] == '"':
                    j += 1
                    break
                j += 1
            result.append(q[i:j])
            i = j
            continue
        if ch == "{":
            result.append(" {\n")
            depth += 1
            result.append(pad * depth)
        elif ch == "}":
            depth = max(0, depth - 1)
            result.append("\n" + pad * depth + "}")
        elif ch in ("\n", "\r", " ", "\t"):
            if result and result[-1] not in ("\n", " ", "{\n"):
                result.append(" ")
        else:
            result.append(ch)
        i += 1

    return "".join(result).strip()


query = """
query GetUser($id: ID!) {user(id: $id) {id name email posts {title}}}
"""
print(format_graphql(query))

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.