ASP.NET Core中使用GraphQL - 第四章 GraphiQL

ASP.NET Core中使用GraphQLjavascript


<code>GraphiQL</code>是一款内置在浏览器中的<code>GraphQL</code>探索工具,这个是开发<code>GraphQL</code>的一个必备工具。它就至关于WebApi中的Swagger, 使用这个工具就能够看到你的<code>GraphQL中</code>全部配置的结构,并能够在浏览器中测试你的<code>query</code>, <code>mutation</code>css

如今除了<code>GraphiQL</code>, <code>graphql-dotnet</code>还提供了另一个[GraphQL.Server](GraphQL for .NET - Subscription Transport WebSockets)的类库, 它也能够生成一个界面更优雅的探索工具,可是因为做者声明了还未在重型生产环境中测试过,因此这里先不作介绍,后续我会单独写一篇博文来介绍一下。html

要想使用<code>GraphiQL</code>, 咱们须要借助NodeJs中的npm和webpack.java

首先咱们在当前Hello World项目中建立一个package.json文件, 内容以下node

{
  "name": "GraphQLAPI",
  "version": "1.0.0",
  "main": "index.js",
  "author": "Fiyaz Hasan",
  "license": "MIT",
  "dependencies": {
    "graphiql": "^0.11.11",
    "graphql": "^0.13.2",
    "isomorphic-fetch": "^2.2.1",
    "react": "^16.3.1",
    "react-dom": "^16.2.0"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^0.28.11",
    "extract-text-webpack-plugin": "^3.0.2",
    "ignore-loader": "^0.1.2",
    "style-loader": "^0.20.3",
    "webpack": "^3.11.0"
  }
}

而后可使用一下命令,安装package.json中全部预约义的库react

npm install

下一步,咱们须要在当前项目目录中建立一个新的文件夹<code>ClientApp</code>, 并在其中添加2个文件<code>app.js</code>和<code>app.css</code>, 其文件内容以下。webpack

app.js
import React from 'react';  
import ReactDOM from 'react-dom';  
import GraphiQL from 'graphiql';  
import fetch from 'isomorphic-fetch';  
import 'graphiql/graphiql.css';  
import './app.css';

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

ReactDOM.render(  
  <GraphiQL fetcher={graphQLFetcher} />,
  document.getElementById('app')
);
app.css
html, body {  
    height: 100%;
    margin: 0;
    overflow: hidden;
    width: 100%
}

#app {
    height: 100vh
}

<code>GraphiQL</code>是一个客户端库,它提供了一个<code>React</code>组件<code><GraphiQL /></code>, 这个组件用来呈现整个用户界面。这个组件有一个<code>fetcher</code>属性, 这个属性能够附加一个<code>function</code>。 附加的<code>function</code>返回了一个HTTP promise对象,它仅仅是模仿了咱们在Postman中测试的POST请求。因此这些设置都写在<code>app.js</code>文件中。git

下一步咱们须要在<code>wwwroot</code>目录中添加一个<code>index.html</code>, 这里咱们会将<code><GraphiQL /></code>组件的内容呈如今<code>id="app"</code>的<code>div</code>中.github

index.html
<!DOCTYPE html>  
<html>  
<head>  
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>GraphiQL</title>
    <link rel="stylesheet" href="/style.css" />
</head>  
<body>  
    <div id="app"></div>
    <script src="/bundle.js" type="text/javascript"></script>
</body>  
</html>

在<code>index.html</code>文件中,咱们引入了一个<code>bundle.js</code>和一个<code>style.css</code>文件。这2个文件是经过脚本编译出来的,因此这里咱们须要添加一个<code>webpack.config.js</code>web

webpack.config.js
const webpack = require('webpack');  
var path = require('path');  
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = [  
    {
        entry: {
            'bundle': './ClientApp/app.js',
        },

        output: {
            path: path.resolve('./wwwroot'),
            filename: '[name].js'
        },

        resolve: {
            extensions: ['.js', '.json']
        },

        module: {
            rules: [
                { test: /\.js/, use: [{
                    loader: 'babel-loader'
                }], exclude: /node_modules/ },
                {
                    test: /\.css$/, use: ExtractTextPlugin.extract({
                        fallback: "style-loader",
                        use: "css-loader"
                    })
                },
                { test: /\.flow/, use: [{
                    loader: 'ignore-loader'
                }] }
            ]
        },

        plugins: [
            new ExtractTextPlugin('style.css', { allChunks: true })
        ]
    }
];

最后咱们还须要添加一个.babelrc文件,其内容以下

.babelrc
{
  "presets": ["env", "react"]
}

以上文件添加完成以后,咱们能够在在命令行使用<code>webpack</code>命令编译生成这2个文件。

C:\chapter4>webpack
Hash: e8082714ec56e818e1f4
Version: webpack 3.12.0
Child
    Hash: e8082714ec56e818e1f4
    Time: 6645ms
        Asset     Size  Chunks                    Chunk Names
    bundle.js  2.76 MB       0  [emitted]  [big]  bundle
    style.css  39.7 kB       0  [emitted]         bundle
      [33] (webpack)/buildin/global.js 509 bytes {0} [built]
     [128] ./node_modules/graphql-language-service-interface/dist ^.*$ 807 bytes {0} [built]
     [137] ./ClientApp/app.js 996 bytes {0} [built]
     [234] (webpack)/buildin/module.js 517 bytes {0} [built]
     [292] ./ClientApp/app.css 41 bytes {0} [built]
     [297] ./node_modules/css-loader!./ClientApp/app.css 301 bytes [built]
        + 292 hidden modules
    Child extract-text-webpack-plugin node_modules/extract-text-webpack-plugin/dist node_modules/css-loader/index.js!node_modules/graphiql/graphiql.css:
           2 modules
    Child extract-text-webpack-plugin node_modules/extract-text-webpack-plugin/dist node_modules/css-loader/index.js!ClientApp/app.css:
           [0] ./node_modules/css-loader!./ClientApp/app.css 301 bytes {0} [built]
            + 1 hidden module

C:\chapter4>

在服务器端,咱们须要修改<code>Startup.cs</code>文件,在<code>Configure</code>方法中添加静态文件中间件和默认页中间件,修改后最终的<code>Configure</code>方法代码以下

public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
{
    app.UseDefaultFiles();
    app.UseStaticFiles();

    app.UseMiddleware<GraphQLMiddleware>();
}

如今咱们启动项目,你将会看到以下图所示的用户界面。

在右侧的Documentation Explorer面板中,你能够看到定义的全部<code>query</code>, 而且能够了解到哪些字段是可用的,以及它们是干什么用的。

<code>GraphiQL</code>提供了许多很棒的功能

  • 语法高亮
  • 编写<code>GraphQL</code>查询时,字段,参数,类型等的自动感知
  • 实时错误高亮以及报告
  • 自动补全查询
  • 能够在浏览器中模拟请求, 运行检查查询结果

本文源代码:https://github.com/lamondlu/GraphQL_Blogs/tree/master/Part%20IV

相关文章
相关标签/搜索