@8base/graphiql 中文文档教程

发布于 3年前 浏览 25 项目主页 更新于 3年前

GraphiQL

/ˈɡrafək(ə)l/ 图形交互式浏览器内 GraphQL IDE。 尝试现场演示

构建状态CDNJSnpm< /a>

Getting started

使用 node.js 服务器? 只需使用 express-graphql! 它可以自动呈现 GraphiQL。 使用另一个 GraphQL 服务? GraphiQL 非常容易设置。 使用 npm

npm install --save graphiql

或者,如果您使用 yarn

yarn add graphiql

GraphiQL 提供了一个 React 组件负责为了渲染 UI,它应该提供一个从 GraphQL 获取的函数,我们建议使用 fetch 标准 API。

import React from 'react';
import ReactDOM from 'react-dom';
import GraphiQL from 'graphiql';
import fetch from 'isomorphic-fetch';

function graphQLFetcher(graphQLParams) {
  return fetch(window.location.origin + '/graphql', {
    method: 'post',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(graphQLParams),
  }).then(response => response.json());
}

ReactDOM.render(<GraphiQL fetcher={graphQLFetcher} />, document.body);

使用 webpackbrowserify 构建网络,或使用预捆绑的 graphiql.js 文件。 请参阅 git 存储库中的示例,了解如何使用预捆绑文件。

不要忘记在页面上包含 CSS 文件! 如果您使用的是 npmyarn,您可以在 node_modules/graphiql/graphiql.css 中找到它,或者您可以从发布页面

有关设置 GraphiQL 的示例,请查看此存储库中的示例,其中还包括一些突出显示 GraphiQL API 的有用功能。

Features

  • Syntax highlighting
  • Intelligent type ahead of fields, arguments, types, and more.
  • Real-time error highlighting and reporting.
  • Automatic query completion.
  • Run and inspect query results.

Usage

GraphiQL 导出一个旨在包含整个浏览器视口的 React 组件。 这个 React 组件呈现 GraphiQL 编辑器。

import GraphiQL from 'graphiql';

<GraphiQL />

GraphiQL 通过接受 React props 和 children 来支持 UI 和行为的定制。

Props:

  • fetcher:一个接受 GraphQL-HTTP 参数并返回解析为 GraphQL 解析的 JSON 响应的 Promise 或 Observable 的函数。

  • schema:GraphQLSchema 实例或 null(如果不使用的话)。 如果提供了 undefined,GraphiQL 将使用 fetcher 发送一个内省查询来生成一个模式。

  • query:一个可选的 GraphQL 字符串,用作初始显示的查询,如果提供了 undefined,将使用存储的查询或 defaultQuery

  • variables:一个可选的 GraphQL 字符串,用作初始显示的查询变量,如果提供了 undefined,将使用存储的变量。

  • operationName:应执行的 GraphQL 操作的可选名称。

  • response:一个可选的 JSON 字符串,用作初始显示的响应。 如果未提供,则最初不会显示任何响应。 如果说明初始查询的结果,您可以提供此信息。

  • storage:[Storage][] GraphiQL 的实例将用于持久化状态。 默认值:window.localStorage

  • defaultQuery:一个可选的 GraphQL 字符串,当没有提供查询并且之前的会话中不存在存储的查询时使用。 如果提供了 undefined,GraphiQL 将使用它自己的默认查询。

  • onEditQuery:一个可选函数,当查询编辑器发生变化时将被调用。 该函数的参数将是查询字符串。

  • onEditVariables:一个可选函数,当查询变量编辑器发生变化时将被调用。 函数的参数将是变量字符串。

  • onEditOperationName:可选函数,当要执行的操作名称改变时调用。

  • onToggleDocs:一个可选函数,将在切换文档时调用。 该函数的参数将是一个布尔值,无论文档现在是打开还是关闭。

  • getDefaultFieldNames:一个可选函数,用于向无效地缺少选择集的非叶字段提供默认字段。 接受一个 GraphQLType 实例并返回一个字段名称数组。 如果未提供,将使用默认行为。

  • editorTheme:一个可选字符串,命名要应用于 QueryEditorResultViewerVariables 窗格的 CodeMirror 主题。 默认为 graphiql 主题。 请参阅下面的完整用法。

儿童:

  • :将 GraphiQL 徽标替换为您自己的徽标。

  • :在GraphiQL之上添加自定义工具栏。 如果没有提供,一个 默认工具栏可能包含常用操作。 传递空 如果需要一个空的工具栏。

  • :在 GraphiQL 上方的工具栏中添加一个按钮。

  • :在 GraphiQL 上方的工具栏中添加下拉菜单。

  • :菜单项。

  • :在GraphiQL上方的工具栏中添加一个选择列表。

  • :选择列表的选项。

  • :添加一组关联控件到 GraphiQL 上方的工具栏。 期望孩子是 ,或

  • :在 GraphiQL 结果下方添加自定义页脚。

Usage Examples

class CustomGraphiQL extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // REQUIRED:
      // `fetcher` must be provided in order for GraphiQL to operate
      fetcher: this.props.fetcher,

      // OPTIONAL PARAMETERS
      // GraphQL artifacts
      query: '',
      variables: '',
      response: '',

      // GraphQL Schema
      // If `undefined` is provided, an introspection query is executed
      // using the fetcher.
      schema: undefined,

      // Useful to determine which operation to run
      // when there are multiple of them.
      operationName: null,
      storage: null,
      defaultQuery: null,

      // Custom Event Handlers
      onEditQuery: null,
      onEditVariables: null,
      onEditOperationName: null,

      // GraphiQL automatically fills in leaf nodes when the query
      // does not provide them. Change this if your GraphQL Definitions
      // should behave differently than what's defined here:
      // (https://github.com/graphql/graphiql/blob/master/src/utility/fillLeafs.js#L75)
      getDefaultFieldNames: null
    };
  }

  // Example of using the GraphiQL Component API via a toolbar button.
  handleClickPrettifyButton(event) {
    const editor = this.graphiql.getQueryEditor();
    const currentText = editor.getValue();
    const { parse, print } = require('graphql');
    const prettyText = print(parse(currentText));
    editor.setValue(prettyText);
  }

  render() {
    return (
      <GraphiQL ref={c => { this.graphiql = c; }} {...this.state}>
        <GraphiQL.Logo>
          Custom Logo
        </GraphiQL.Logo>
        <GraphiQL.Toolbar>

          // GraphiQL.Button usage
          <GraphiQL.Button
            onClick={this.handleClickPrettifyButton}
            label="Prettify"
            title="Prettify Query (Shift-Ctrl-P)"
          />

          // Some other possible toolbar items
          <GraphiQL.Menu label="File" title="File">
            <GraphiQL.MenuItem label="Save" title="Save" onSelect={...}>
          </GraphiQL.Menu>

          <OtherReactComponent someProps="true" />

        </GraphiQL.Toolbar>
        <GraphiQL.Footer>
          // Footer works the same as Toolbar
          // add items by appending child components
        </GraphiQL.Footer>
      </GraphiQL>
    );
  }
}

Applying an Editor Theme

为了给界面的编辑器部分设置主题,您可以提供一个 editorTheme 道具。 您还需要为主题加载适当的 CSS(类似于为该项目加载 CSS)。 在此处查看可用的主题

// In your html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.23.0/theme/solarized.css" />

// In your GraphiQL JSX
<GraphiQL
  editorTheme="solarized light"
/>

Query Samples

查询

GraphQL 查询以声明的方式描述发行者希望从任何执行 GraphQL 查询的人那里获取哪些数据。

query FetchSomeIDQuery($someId: String!) {
  human(id: $someId) {
    name
  }
}

更多示例可从:GraphQL Queries 获得。

Mutation

给定此模式,

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    fields: {
      numberHolder: { type: numberHolderType },
    },
    name: 'Query',
  }),
  mutation: new GraphQLObjectType({
    fields: {
      immediatelyChangeTheNumber: {
        type: numberHolderType,
        args: { newNumber: { type: GraphQLInt } },
        resolve: (function (obj, { newNumber }) {
          return obj.immediatelyChangeTheNumber(newNumber);
        })
      }
    },
    name: 'Mutation',
  })
});

则可以进行以下变异查询:

mutation TestMutation {
  first: immediatelyChangeTheNumber(newNumber: 1) {
    theNumber
  }
}

graphql-js 中的这个突变测试。

Relay 有另一个很好的例子,它使用通用模式来组合突变。 给定以下 GraphQL 类型定义,

input IntroduceShipInput {
  factionId: ID!
  shipName: String!
  clientMutationId: String!
}

type IntroduceShipPayload {
  faction: Faction
  ship: Ship
  clientMutationId: String!
}

突变调用是这样组成的:

mutation AddBWingQuery($input: IntroduceShipInput!) {
  introduceShip(input: $input) {
    ship {
      id
      name
    }
    faction {
      name
    }
    clientMutationId
  }
}
{
  "input": {
    "shipName": "B-Wing",
    "factionId": "1",
    "clientMutationId": "abcde"
  }
}

Relay 阅读更多内容突变文档

片段

片段允许重复使用常见的重复选择字段,减少文档中的重复文本。 内联片段可以直接在选择中使用,以在查询接口或联合时以类型条件为条件。 因此,代替以下查询:

{
  luke: human(id: "1000") {
    name
    homePlanet
  }
  leia: human(id: "1003") {
    name
    homePlanet
  }
}

使用片段,以下查询是可能的。

{
  luke: human(id: "1000") {
    ...HumanFragment
  }
  leia: human(id: "1003") {
    ...HumanFragment
  }
}

fragment HumanFragment on Human {
  name
  homePlanet
}

GraphQL 片段规范 阅读更多内容。

GraphiQL

/ˈɡrafək(ə)l/ A graphical interactive in-browser GraphQL IDE. Try the live demo.

Build StatusCDNJSnpm

Getting started

Using a node.js server? Just use express-graphql! It can automatically present GraphiQL. Using another GraphQL service? GraphiQL is pretty easy to set up. With npm:

npm install --save graphiql

Alternatively, if you are using yarn:

yarn add graphiql

GraphiQL provides a React component responsible for rendering the UI, which should be provided with a function for fetching from GraphQL, we recommend using the fetch standard API.

import React from 'react';
import ReactDOM from 'react-dom';
import GraphiQL from 'graphiql';
import fetch from 'isomorphic-fetch';

function graphQLFetcher(graphQLParams) {
  return fetch(window.location.origin + '/graphql', {
    method: 'post',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(graphQLParams),
  }).then(response => response.json());
}

ReactDOM.render(<GraphiQL fetcher={graphQLFetcher} />, document.body);

Build for the web with webpack or browserify, or use the pre-bundled graphiql.js file. See the example in the git repository to see how to use the pre-bundled file.

Don't forget to include the CSS file on the page! If you're using npm or yarn, you can find it in node_modules/graphiql/graphiql.css, or you can download it from the releases page.

For an example of setting up a GraphiQL, check out the example in this repository which also includes a few useful features highlighting GraphiQL's API.

Features

  • Syntax highlighting
  • Intelligent type ahead of fields, arguments, types, and more.
  • Real-time error highlighting and reporting.
  • Automatic query completion.
  • Run and inspect query results.

Usage

GraphiQL exports a single React component which is intended to encompass the entire browser viewport. This React component renders the GraphiQL editor.

import GraphiQL from 'graphiql';

<GraphiQL />

GraphiQL supports customization in UI and behavior by accepting React props and children.

Props:

  • fetcher: a function which accepts GraphQL-HTTP parameters and returns a Promise or Observable which resolves to the GraphQL parsed JSON response.

  • schema: a GraphQLSchema instance or null if one is not to be used. If undefined is provided, GraphiQL will send an introspection query using the fetcher to produce a schema.

  • query: an optional GraphQL string to use as the initial displayed query, if undefined is provided, the stored query or defaultQuery will be used.

  • variables: an optional GraphQL string to use as the initial displayed query variables, if undefined is provided, the stored variables will be used.

  • operationName: an optional name of which GraphQL operation should be executed.

  • response: an optional JSON string to use as the initial displayed response. If not provided, no response will be initially shown. You might provide this if illustrating the result of the initial query.

  • storage: an instance of [Storage][] GraphiQL will use to persist state. Default: window.localStorage.

  • defaultQuery: an optional GraphQL string to use when no query is provided and no stored query exists from a previous session. If undefined is provided, GraphiQL will use its own default query.

  • onEditQuery: an optional function which will be called when the Query editor changes. The argument to the function will be the query string.

  • onEditVariables: an optional function which will be called when the Query variable editor changes. The argument to the function will be the variables string.

  • onEditOperationName: an optional function which will be called when the operation name to be executed changes.

  • onToggleDocs: an optional function which will be called when the docs will be toggled. The argument to the function will be a boolean whether the docs are now open or closed.

  • getDefaultFieldNames: an optional function used to provide default fields to non-leaf fields which invalidly lack a selection set. Accepts a GraphQLType instance and returns an array of field names. If not provided, a default behavior will be used.

  • editorTheme: an optional string naming a CodeMirror theme to be applied to the QueryEditor, ResultViewer, and Variables panes. Defaults to the graphiql theme. See below for full usage.

Children:

  • <GraphiQL.Logo>: Replace the GraphiQL logo with your own.

  • <GraphiQL.Toolbar>: Add a custom toolbar above GraphiQL. If not provided, a default toolbar may contain common operations. Pass the empty <GraphiQL.Toolbar /> if an empty toolbar is desired.

  • <GraphiQL.Button>: Add a button to the toolbar above GraphiQL.

  • <GraphiQL.Menu>: Add a dropdown menu to the toolbar above GraphiQL.

  • <GraphiQL.MenuItem>: Items for a menu.

  • <GraphiQL.Select>: Add a select list to the toolbar above GraphiQL.

  • <GraphiQL.SelectOption>: Options for a select list.

  • <GraphiQL.Group>: Add a group of associated controls to the toolbar above GraphiQL. Expects children to be <GraphiQL.Button>, <GraphiQL.Menu>, or <GraphiQL.Select>.

  • <GraphiQL.Footer>: Add a custom footer below GraphiQL Results.

Usage Examples

class CustomGraphiQL extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // REQUIRED:
      // `fetcher` must be provided in order for GraphiQL to operate
      fetcher: this.props.fetcher,

      // OPTIONAL PARAMETERS
      // GraphQL artifacts
      query: '',
      variables: '',
      response: '',

      // GraphQL Schema
      // If `undefined` is provided, an introspection query is executed
      // using the fetcher.
      schema: undefined,

      // Useful to determine which operation to run
      // when there are multiple of them.
      operationName: null,
      storage: null,
      defaultQuery: null,

      // Custom Event Handlers
      onEditQuery: null,
      onEditVariables: null,
      onEditOperationName: null,

      // GraphiQL automatically fills in leaf nodes when the query
      // does not provide them. Change this if your GraphQL Definitions
      // should behave differently than what's defined here:
      // (https://github.com/graphql/graphiql/blob/master/src/utility/fillLeafs.js#L75)
      getDefaultFieldNames: null
    };
  }

  // Example of using the GraphiQL Component API via a toolbar button.
  handleClickPrettifyButton(event) {
    const editor = this.graphiql.getQueryEditor();
    const currentText = editor.getValue();
    const { parse, print } = require('graphql');
    const prettyText = print(parse(currentText));
    editor.setValue(prettyText);
  }

  render() {
    return (
      <GraphiQL ref={c => { this.graphiql = c; }} {...this.state}>
        <GraphiQL.Logo>
          Custom Logo
        </GraphiQL.Logo>
        <GraphiQL.Toolbar>

          // GraphiQL.Button usage
          <GraphiQL.Button
            onClick={this.handleClickPrettifyButton}
            label="Prettify"
            title="Prettify Query (Shift-Ctrl-P)"
          />

          // Some other possible toolbar items
          <GraphiQL.Menu label="File" title="File">
            <GraphiQL.MenuItem label="Save" title="Save" onSelect={...}>
          </GraphiQL.Menu>

          <OtherReactComponent someProps="true" />

        </GraphiQL.Toolbar>
        <GraphiQL.Footer>
          // Footer works the same as Toolbar
          // add items by appending child components
        </GraphiQL.Footer>
      </GraphiQL>
    );
  }
}

Applying an Editor Theme

In order to theme the editor portions of the interface, you can supply a editorTheme prop. You'll also need to load the appropriate CSS for the theme (similar to loading the CSS for this project). See the themes available here.

// In your html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.23.0/theme/solarized.css" />

// In your GraphiQL JSX
<GraphiQL
  editorTheme="solarized light"
/>

Query Samples

Query

GraphQL queries declaratively describe what data the issuer wishes to fetch from whoever is fulfilling the GraphQL query.

query FetchSomeIDQuery($someId: String!) {
  human(id: $someId) {
    name
  }
}

More examples available from: GraphQL Queries.

Mutation

Given this schema,

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    fields: {
      numberHolder: { type: numberHolderType },
    },
    name: 'Query',
  }),
  mutation: new GraphQLObjectType({
    fields: {
      immediatelyChangeTheNumber: {
        type: numberHolderType,
        args: { newNumber: { type: GraphQLInt } },
        resolve: (function (obj, { newNumber }) {
          return obj.immediatelyChangeTheNumber(newNumber);
        })
      }
    },
    name: 'Mutation',
  })
});

then the following mutation queries are possible:

mutation TestMutation {
  first: immediatelyChangeTheNumber(newNumber: 1) {
    theNumber
  }
}

Read more in this mutation test in graphql-js.

Relay has another good example using a common pattern for composing mutations. Given the following GraphQL Type Definitions,

input IntroduceShipInput {
  factionId: ID!
  shipName: String!
  clientMutationId: String!
}

type IntroduceShipPayload {
  faction: Faction
  ship: Ship
  clientMutationId: String!
}

mutation calls are composed as such:

mutation AddBWingQuery($input: IntroduceShipInput!) {
  introduceShip(input: $input) {
    ship {
      id
      name
    }
    faction {
      name
    }
    clientMutationId
  }
}
{
  "input": {
    "shipName": "B-Wing",
    "factionId": "1",
    "clientMutationId": "abcde"
  }
}

Read more from Relay Mutation Documentation.

Fragment

Fragments allow for the reuse of common repeated selections of fields, reducing duplicated text in the document. Inline Fragments can be used directly within a selection to condition upon a type condition when querying against an interface or union. Therefore, instead of the following query:

{
  luke: human(id: "1000") {
    name
    homePlanet
  }
  leia: human(id: "1003") {
    name
    homePlanet
  }
}

using fragments, the following query is possible.

{
  luke: human(id: "1000") {
    ...HumanFragment
  }
  leia: human(id: "1003") {
    ...HumanFragment
  }
}

fragment HumanFragment on Human {
  name
  homePlanet
}

Read more from GraphQL Fragment Specification.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文