跳到内容
🛠️ToolsShed

GraphQL查询格式化器

使用正确的缩进格式化和美化GraphQL查询、变更、订阅和片段。

关于此工具

GraphQL是一种强大的API查询语言,但在处理复杂的查询、变更和订阅时,原始文本会变得难以阅读和调试。GraphQL Query Formatter会自动重新格式化未格式化或格式不规范的GraphQL代码,添加适当的缩进和间距,使其一目了然。这在与API集成、测试不同的查询结构或与需要审查代码的团队成员协作时特别有价值。

使用这个工具非常简单:将GraphQL查询、变更、订阅或片段粘贴到输入框中,然后单击格式化按钮。格式化程序会立即分析代码,添加适当的缩进,对齐嵌套的字段和参数,并确保整个代码的间距一致。然后,您可以复制格式化后的结果,并在项目、文档或API测试工具中使用。它可以处理复杂的场景,包括嵌套选择、别名、变量、指令和内联片段。

这个工具对于使用Apollo Client、Relay或任何GraphQL客户端库的开发者,以及管理GraphQL服务器的后端工程师特别有帮助。与手动格式化相比,它节省了时间,并有助于在向API发送请求之前发现语法问题。无论您是在学习GraphQL、调试复杂查询还是准备代码供审查,使用可靠的格式化程序都能确保您的查询始终清晰专业。

常见问题

代码实现

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.