获取 GraphQL 整个模式查询

Get GraphQL whole schema query

我想从服务器获取架构。 我可以获取所有类型的实体,但无法获取属性。

获取所有类型:

query {
  __schema {
    queryType {
      fields {
        name
        type {
          kind
          ofType {
            kind
            name
          }
        }
      }
    }
  }
}

如何获取类型的属性:

__type(name: "Person") {
    kind
    name
    fields {
      name
      type {
        kind
        name
        description
      }
    }
  }

如何仅在 1 个请求中获取具有属性的所有类型?或者更好:我怎样才能得到整个模式与突变器、枚举、类型...

您可以使用 GraphQL-JS 的内省查询来获取您想要了解的关于架构的所有信息:

import { introspectionQuery } from 'graphql';

如果您只需要类型的信息,您可以使用这个:

{
    __schema: {
        types: {
            ...fullType
        }
    }
}

它使用自省查询中的以下片段:

fragment FullType on __Type {
    kind
    name
    description
    fields(includeDeprecated: true) {
      name
      description
      args {
        ...InputValue
      }
      type {
        ...TypeRef
      }
      isDeprecated
      deprecationReason
    }
    inputFields {
      ...InputValue
    }
    interfaces {
      ...TypeRef
    }
    enumValues(includeDeprecated: true) {
      name
      description
      isDeprecated
      deprecationReason
    }
    possibleTypes {
      ...TypeRef
    }
  }
  fragment InputValue on __InputValue {
    name
    description
    type { ...TypeRef }
    defaultValue
  }
  fragment TypeRef on __Type {
    kind
    name
    ofType {
      kind
      name
      ofType {
        kind
        name
        ofType {
          kind
          name
          ofType {
            kind
            name
            ofType {
              kind
              name
              ofType {
                kind
                name
                ofType {
                  kind
                  name
                }
              }
            }
          }
        }
      }
    }
  }
`;

如果这看起来很复杂,那是因为字段可以任意深入地包裹在非空值和列表中,这意味着如果您的字段包裹在超过 7 层(这可能不是这样的)。

您可以查看introspectionQuery的源代码here

更新

现在推荐使用 graphql-cli 获取和更新架构。

以下命令将帮助您入门:

# install via NPM
npm install -g graphql-cli

# Setup your .graphqlconfig file (configure endpoints + schema path)
graphql init

# Download the schema from the server
graphql get-schema

您甚至可以通过 运行:

监听模式更改并持续更新您的模式
graphql get-schema --watch

In case you just want to download the GraphQL schema, use the following approach:

获取 GraphQL 模式的最简单方法是使用 CLI 工具 get-graphql-schema

您可以通过 NPM 安装它:

npm install -g get-graphql-schema

有两种获取架构的方法。 1) GraphQL IDL 格式或 2) JSON 自省查询格式。

GraphQL IDL 格式

get-graphql-schema ENDPOINT_URL > schema.graphql

JSON自省格式

get-graphql-schema ENDPOINT_URL --json > schema.json

get-graphql-schema ENDPOINT_URL -j > schema.json

更多信息可以参考以下教程:How to download the GraphQL IDL Schema

如果您想自己做,请阅读这些代码:

有一个模块化的最先进的工具「graphql-cli」,考虑看看它。它使用包「graphql」的 buildClientSchema 从内省数据构建 IDL .graphql 文件。

这是GraphiQL使用的查询(网络捕获):

query IntrospectionQuery {
  __schema {
    queryType {
      name
    }
    mutationType {
      name
    }
    subscriptionType {
      name
    }
    types {
      ...FullType
    }
    directives {
      name
      description
      locations
      args {
        ...InputValue
      }
    }
  }
}

fragment FullType on __Type {
  kind
  name
  description
  fields(includeDeprecated: true) {
    name
    description
    args {
      ...InputValue
    }
    type {
      ...TypeRef
    }
    isDeprecated
    deprecationReason
  }
  inputFields {
    ...InputValue
  }
  interfaces {
    ...TypeRef
  }
  enumValues(includeDeprecated: true) {
    name
    description
    isDeprecated
    deprecationReason
  }
  possibleTypes {
    ...TypeRef
  }
}

fragment InputValue on __InputValue {
  name
  description
  type {
    ...TypeRef
  }
  defaultValue
}

fragment TypeRef on __Type {
  kind
  name
  ofType {
    kind
    name
    ofType {
      kind
      name
      ofType {
        kind
        name
        ofType {
          kind
          name
          ofType {
            kind
            name
            ofType {
              kind
              name
              ofType {
                kind
                name
              }
            }
          }
        }
      }
    }
  }
}

您可以使用以下命令下载远程 GraphQL 服务器的架构。命令成功后,您应该会在当前工作目录中看到一个名为 schema.json 的新文件。

~$ npx apollo-cli download-schema $GRAPHQL_URL --output schema.json

你可以使用 IntelliJ 插件 JS GraphQL 然后 IDEA 会要求你创建两个文件 "graphql.config.json" 和 "graphql.schema.json"

然后您可以编辑 "graphql.config.json" 以指向您的本地或远程 GraphQL 服务器:

"schema": {
"README_request" : "To request the schema from a url instead, remove the 'file' JSON property above (and optionally delete the default graphql.schema.json file).",
"request": {
  "url" : "http://localhost:4000",
  "method" : "POST",
  "README_postIntrospectionQuery" : "Whether to POST an introspectionQuery to the url. If the url always returns the schema JSON, set to false and consider using GET",
  "postIntrospectionQuery" : true,
  "README_options" : "See the 'Options' section at https://github.com/then/then-request",
  "options" : {
    "headers": {
      "user-agent" : "JS GraphQL"
    }
  }
}

之后,IDEA 插件将从 GraphQL 服务器自动加载架构,并在控制台中显示架构 json,如下所示:

Loaded schema from 'http://localhost:4000': {"data":{"__schema":{"queryType":{"name":"Query"},"mutationType":{"name":"Mutation"},"subscriptionType":null,"types":[{"kind":"OBJECT","name":"Query","description":"","fields":[{"name":"launche

您可以使用 apollo codegen:client。参见 https://github.com/apollographql/apollo-tooling#apollo-clientcodegen-output

使用apollo cli:

npx apollo schema:download --endpoint=http://localhost:4000/graphql schema.json

参考

想指出的是,如果需要身份验证,您可能不能只使用从 graphql init

生成的配置文件

你可能需要做这样的事情,例如,使用 github graphql API

{
  "projects": {
    "graphqlProjectTestingGraphql": {
      "schemaPath": "schema.graphql",
      "extensions": {
        "endpoints": {
          "dev": {
            "url": "https://api.github.com/graphql",
            "headers": {
              "Authorization": "Bearer <Your token here>"
            }
          }
        }
      }
    }
  }
}

您可以使用 Hasura 的 graphqurl 实用程序

npm install -g graphqurl

gq <endpoint> --introspect > schema.graphql

# or if you want it in json
gq <endpoint> --introspect --format json > schema.json

完整文档:https://github.com/hasura/graphqurl

您可以使用GraphQL-Codegen with the ast-plugin

npm install --save graphql
npm install --save-dev @graphql-codegen/cli
npx graphql-codegen init

按照步骤生成 codegen.yml 文件

安装工具后,您可以使用插件下载schema-ast

的架构

最好按照页面上的说明进行安装……但基本上:

npm install --save-dev @graphql-codegen/schema-ast

然后配置 codegen.yml 文件以设置哪个模式 is/are 真实来源以及将下载的模式文件放在哪里:

schema:
  - 'http://localhost:3000/graphql'
generates:
  path/to/file.graphql:
    plugins:
      - schema-ast
    config:
      includeDirectives: true

更新

在厌倦了一直修改我以前的脚本之后,我屈服了并制作了自己的 CLI 工具 gql-sdl。我仍然找不到可以使用零配置下载 GraphQL SDL 的不同工具,但希望有一个工具存在。

基本用法:

$ gql-sdl https://api.github.com/graphql -H "Authorization: Bearer ghp_[redacted]"
directive @requiredCapabilities(requiredCapabilities: [String!]) on OBJECT | SCALAR | ARGUMENT_DEFINITION | INTERFACE | INPUT_OBJECT | FIELD_DEFINITION | ENUM | ENUM_VALUE | UNION | INPUT_FIELD_DEFINITION

"""Autogenerated input type of AbortQueuedMigrations"""
input AbortQueuedMigrationsInput {
  """The ID of the organization that is running the migrations."""
  ownerId: ID!

  """A unique identifier for the client performing the mutation."""
  clientMutationId: String
}
...

header 参数 -H 在技术上是可选的,但大多数 GraphQL API 需要通过 headers 进行身份验证。您也可以下载 JSON 响应而不是 (--json),但这是一个已经被其他工具很好地服务的用例。

在幕后,它仍然使用 GraphQL.js 提供的内省查询,因此如果您希望将此功能合并到您自己的代码中,请参见下面的示例。


上一个回答

不知何故,我无法获得任何建议的 CLI 工具来输出 GraphQL 的模式定义语言 (SDL) 中的模式,而不是内省结果 JSON。我最终拼凑了一个非常快速的 Node 脚本来让 GraphQL 库为我做这件事:

const fs = require("fs");
const { buildClientSchema, getIntrospectionQuery, printSchema } = require("graphql");
const fetch = require("node-fetch");

async function saveSchema(endpoint, filename) {
    const response = await fetch(endpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ query: getIntrospectionQuery() })
    });
    const graphqlSchemaObj = buildClientSchema((await response.json()).data);
    const sdlString = printSchema(graphqlSchemaObj);
    fs.writeFileSync(filename, sdlString);
}

saveSchema("https://example.com/graphql", "schema.graphql");

getIntrospectionQuery() 有完整的内省查询,你需要得到一切,然后 buildClientSchema()printSchema() 将 JSON 混乱变成 GraphQL SDL。

把它变成一个 CLI 工具本身并不难,但感觉有点过头了。

我也在看这个 Medium article on GraphQL

下面的查询返回了许多关于架构、查询及其输入和输出参数类型的详细信息。

fragment FullType on __Type {
  kind
  name
  fields(includeDeprecated: true) {
    name
    args {
      ...InputValue
    }
    type {
      ...TypeRef
    }
    isDeprecated
    deprecationReason
  }
  inputFields {
    ...InputValue
  }
  interfaces {
    ...TypeRef
  }
  enumValues(includeDeprecated: true) {
    name
    isDeprecated
    deprecationReason
  }
  possibleTypes {
    ...TypeRef
  }
}
fragment InputValue on __InputValue {
  name
  type {
    ...TypeRef
  }
  defaultValue
}
fragment TypeRef on __Type {
  kind
  name
  ofType {
    kind
    name
    ofType {
      kind
      name
      ofType {
        kind
        name
        ofType {
          kind
          name
          ofType {
            kind
            name
            ofType {
              kind
              name
              ofType {
                kind
                name
              }
            }
          }
        }
      }
    }
  }
}
query IntrospectionQuery {
  __schema {
    queryType {
      name
    }
    mutationType {
      name
    }
    types {
      ...FullType
    }
    directives {
      name
      locations
      args {
        ...InputValue
      }
    }
  }
}

graphql npm package's IntrospectionQuery does

query IntrospectionQuery {
    __schema {
        queryType {
            name
        }
        mutationType {
            name
        }
        subscriptionType {
            name
        }
        types {
            ...FullType
        }
        directives {
            name
            description

            locations
            args {
                ...InputValue
            }
        }
    }
}

fragment FullType on __Type {
    kind
    name
    description

    fields(includeDeprecated: true) {
        name
        description
        args {
            ...InputValue
        }
        type {
            ...TypeRef
        }
        isDeprecated
        deprecationReason
    }
    inputFields {
        ...InputValue
    }
    interfaces {
        ...TypeRef
    }
    enumValues(includeDeprecated: true) {
        name
        description
        isDeprecated
        deprecationReason
    }
    possibleTypes {
        ...TypeRef
    }
}

fragment InputValue on __InputValue {
    name
    description
    type {
        ...TypeRef
    }
    defaultValue
}

fragment TypeRef on __Type {
    kind
    name
    ofType {
        kind
        name
        ofType {
            kind
            name
            ofType {
                kind
                name
                ofType {
                    kind
                    name
                    ofType {
                        kind
                        name
                        ofType {
                            kind
                            name
                            ofType {
                                kind
                                name
                            }
                        }
                    }
                }
            }
        }
    }
}

source