簡體   English   中英

獲取 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-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

如果您只想下載 GraphQL 架構,請使用以下方法:

獲取 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

更多信息可以參考以下教程: 如何下載 GraphQL IDL Schema

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

如果這看起來很復雜,那是因為字段可以任意深度包裝在 nonNulls 和 Lists 中,這意味着從技術上講,如果您的字段包裝在 7 層以上(可能不是這種情況),即使上面的查詢也不能反映完整的模式)。

您可以在此處查看 introspectionQuery 的源代碼。

使用 阿波羅 cli

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

您可以使用 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 服務器的架構。 命令成功后,您應該會在當前工作目錄中看到一個名為schema.json的新文件。

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

您可以將GraphQL-Codegen 與 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文件以設置哪些模式是/是事實的來源以及將下載的模式文件放在哪里:

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

標頭參數-H在技術上是可選的,但大多數 GraphQL API 需要通過標頭進行身份驗證。 您也可以改為下載 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 工具本身並不太難,但這感覺有點矯枉過正。

您可以使用 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

我也在尋找並看到這篇關於 GraphQL 的 Medium 文章

以下查詢返回了有關架構、查詢及其輸入和輸出參數類型的許多詳細信息。

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

參考https://stackoverflow.com/a/42010467/10189759

想指出,如果需要身份驗證,您可能不能只使用從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>"
            }
          }
        }
      }
    }
  }
}

如果您想自己做,請閱讀以下代碼:

有一個模塊化的 state-of-art 工具「graphql-cli」,考慮看看它。 它使用包「graphql」的 buildClientSchema 從自省數據構建 IDL .graphql 文件。

1)安裝get-graphql-schema(NPM)

npm install -g get-graphql-schema

2)使用它將架構下載到當前目錄

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

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

資源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM