简体   繁体   English

获取 GraphQL 整个架构查询

[英]Get GraphQL whole schema query

I want to get the schema from the server.我想从服务器获取架构。 I can get all entities with the types but I'm unable to get the properties.我可以获取具有类型的所有实体,但无法获取属性。

Getting all types:获取所有类型:

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

How to get the properties for type:如何获取类型的属性:

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

How can I get all types with the properties in only 1 request?如何仅在 1 个请求中获取具有属性的所有类型? Or ever better: How can I get the whole schema with the mutators, enums, types ...或者更好:我怎样才能获得带有突变器、枚举、类型的整个模式......

Update更新

Using graphql-cli is now the recommended workflow to get and update your schema.现在推荐使用graphql-cli来获取和更新架构。

The following commands will get you started:以下命令将帮助您入门:

# 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

You can even listen for schema changes and continuously update your schema by running:您甚至可以通过运行以下命令来监听架构更改并不断更新您的架构:

graphql get-schema --watch

In case you just want to download the GraphQL schema, use the following approach:如果您只想下载 GraphQL 架构,请使用以下方法:

The easiest way to get a GraphQL schema is using the CLI tool get-graphql-schema .获取 GraphQL 模式的最简单方法是使用 CLI 工具get-graphql-schema

You can install it via NPM:你可以通过 NPM 安装它:

npm install -g get-graphql-schema

There are two ways to get your schema.有两种方法可以获取您的架构。 1) GraphQL IDL format or 2) JSON introspection query format. 1) GraphQL IDL格式或 2) JSON 自省查询格式。

GraphQL IDL format GraphQL IDL 格式

get-graphql-schema ENDPOINT_URL > schema.graphql

JSON introspection format JSON自省格式

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

or或者

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

For more information you can refer to the following tutorial: How to download the GraphQL IDL Schema更多信息可以参考以下教程: 如何下载 GraphQL IDL Schema

This is the query that GraphiQL uses (network capture):这是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
              }
            }
          }
        }
      }
    }
  }
}

You can use GraphQL-JS's introspection query to get everything you'd like to know about the schema:您可以使用 GraphQL-JS 的自省查询来获取您想了解的有关架构的所有信息:

import { introspectionQuery } from 'graphql';

If you want just the information for types, you can use this:如果你只想要类型的信息,你可以使用这个:

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

Which uses the following fragment from the introspection query:它使用自省查询中的以下片段:

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
                }
              }
            }
          }
        }
      }
    }
  }
`;

If that seems complicated, it's because fields can be arbitrarility deeply wrapped in nonNulls and Lists, which means that technically even the query above does not reflect the full schema if your fields are wrapped in more than 7 layers (which probably isn't the case).如果这看起来很复杂,那是因为字段可以任意深度包装在 nonNulls 和 Lists 中,这意味着从技术上讲,如果您的字段包装在 7 层以上(可能不是这种情况),即使上面的查询也不能反映完整的模式)。

You can see the source code for introspectionQuery here .您可以在此处查看 introspectionQuery 的源代码。

使用 阿波罗 cli

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

You can use the Hasura's graphqurl utility您可以使用 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

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

You can download a remote GraphQL server's schema with the following command.您可以使用以下命令下载远程 GraphQL 服务器的架构。 When the command succeeds, you should see a new file named schema.json in the current working directory.命令成功后,您应该会在当前工作目录中看到一个名为schema.json的新文件。

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

You can use GraphQL-Codegen with the ast-plugin您可以将GraphQL-Codegen 与 ast-plugin 一起使用

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

Follow the steps to generate the codegen.yml file按照步骤生成codegen.yml文件

Once the tool is installed, you can use the plugin to download the schema which is schema-ast安装该工具后,您可以使用该插件下载schema-ast 架构

The best is to follow the instruction on the page to install it… but basically:最好是按照页面上的说明进行安装……但基本上:

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

Then configure the codegen.yml file to set which schema(s) is/are the source of truth and where to put the downloaded schema(s) file:然后配置codegen.yml文件以设置哪些模式是/是事实的来源以及将下载的模式文件放在哪里:

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

Update更新

After getting sick of modifying my previous script all the time, I caved and made my own CLI tool gql-sdl .在厌倦了一直修改我以前的脚本之后,我屈服并制作了自己的 CLI 工具gql-sdl I still can't find a different tool that can download GraphQL SDL with zero config but would love for one to exist.我仍然找不到其他工具可以下载具有零配置的 GraphQL SDL,但我希望有一个工具存在。

Basic usage:基本用法:

$ 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
}
...

The header argument -H is technically optional but most GraphQL APIs require authentication via headers.标头参数-H在技术上是可选的,但大多数 GraphQL API 需要通过标头进行身份验证。 You can also download the JSON response instead ( --json ) but that's a use case already well served by other tools.您也可以改为下载 JSON 响应 ( --json ),但这是其他工具已经很好地服务的用例。

Under the hood this still uses the introspection query provided by GraphQL.js , so if you're looking to incorporate this functionality into your own code see the example below.在后台,它仍然使用GraphQL.js提供的自省查询,因此如果您希望将此功能合并到您自己的代码中,请参阅下面的示例。


Previous answer上一个答案

Somehow I wasn't able to get any of the suggested CLI tools to output the schema in GraphQL's Schema Definition Language (SDL) instead of the introspection result JSON.不知何故,我无法获得任何建议的 CLI 工具来输出 GraphQL 的模式定义语言 (SDL) 中的模式,而不是自省结果 JSON。 I ended up throwing together a really quick Node script to make the GraphQL library do it for me:最后我拼凑了一个非常快速的 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() has the complete introspection query you need to get everything, and then buildClientSchema() and printSchema() turns the JSON mess into GraphQL SDL. getIntrospectionQuery()具有获取所有内容所需的完整自省查询,然后buildClientSchema()printSchema()将 JSON 混乱转换为 GraphQL SDL。

Wouldn't be too difficult to make this into a CLI tool itself but that feels like overkill.将它变成 CLI 工具本身并不太难,但这感觉有点矫枉过正。

You can use IntelliJ plugin JS GraphQL then IDEA will ask you create two files "graphql.config.json" and "graphql.schema.json"您可以使用 IntelliJ 插件JS GraphQL然后 IDEA 会要求您创建两个文件“graphql.config.json”和“graphql.schema.json”

Then you can edit "graphql.config.json" to point to your local or remote GraphQL server:然后您可以编辑“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"
    }
  }
}

After that IDEA plugin will auto load schema from GraphQL server and show the schema json in the console like this:之后,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

I was also looking and came across this Medium article on GraphQL我也在寻找并看到这篇关于 GraphQL 的 Medium 文章

The below query returned many details regarding schema, queries and their input & output params type.以下查询返回了有关架构、查询及其输入和输出参数类型的许多详细信息。

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
      }
    }
  }
}

Refer to https://stackoverflow.com/a/42010467/10189759参考https://stackoverflow.com/a/42010467/10189759

Would like to point out that if authentications are needed, that you probably cannot just use the config file generated from graphql init想指出,如果需要身份验证,您可能不能只使用从graphql init生成的配置文件

You might have to do something like this, for example, using the github graphql API你可能需要做这样的事情,例如,使用 github graphql API

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

If you want to do it by your self, read these code:如果您想自己做,请阅读以下代码:

There is a modular state-of-art tool 「graphql-cli」, consider looking at it.有一个模块化的 state-of-art 工具「graphql-cli」,考虑看看它。 It uses package 「graphql」's buildClientSchema to build IDL .graphql file from introspection data.它使用包「graphql」的 buildClientSchema 从自省数据构建 IDL .graphql 文件。

1) Install get-graphql-schema (NPM) 1)安装get-graphql-schema(NPM)

npm install -g get-graphql-schema

2) Use it to download schema to current directory 2)使用它将架构下载到当前目录

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

The graphql npm package's IntrospectionQuery does graphql npm 包的IntrospectionQuery 确实

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 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM