ASP.NET Core中使用GraphQL
- ASP.NET Core中使用GraphQL - 第一章 Hello World
- ASP.NET Core中使用GraphQL - 第二章 中間件
- ASP.NET Core中使用GraphQL - 第三章 依賴注入
GraphiQL
是一款內置在瀏覽器中的GraphQL
探索工具,這個是開發GraphQL
的一個必備工具。它就相當於WebApi中的Swagger, 使用這個工具就可以看到你的GraphQL中
所有配置的結構,並可以在瀏覽器中測試你的query
, mutation
現在除了
GraphiQL
,graphql-dotnet
還提供了另外一個[GraphQL.Server](GraphQL for .NET - Subscription Transport WebSockets)的類庫, 它也可以生成一個界面更優雅的探索工具,但是由於作者聲明了還未在重型生產環境中測試過,所以這里先不做介紹,后續我會單獨寫一篇博文來介紹一下。
要想使用GraphiQL
, 我們需要借助NodeJs中的npm和webpack.
首先我們在當前Hello World項目中創建一個package.json文件, 內容如下
{
"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中所有預定義的庫
npm install
下一步,我們需要在當前項目目錄中創建一個新的文件夾ClientApp
, 並在其中添加2個文件app.js
和app.css
, 其文件內容如下。
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
}
GraphiQL
是一個客戶端庫,它提供了一個React
組件<GraphiQL />
, 這個組件用來呈現整個用戶界面。這個組件有一個fetcher
屬性, 這個屬性可以附加一個function
。 附加的function
返回了一個HTTP promise對象,它僅僅是模仿了我們在Postman中測試的POST請求。所以這些設置都寫在app.js
文件中。
下一步我們需要在wwwroot
目錄中添加一個index.html
, 這里我們會將<GraphiQL />
組件的內容呈現在id="app"
的div
中.
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>
在index.html
文件中,我們引入了一個bundle.js
和一個style.css
文件。這2個文件是通過腳本編譯出來的,所以這里我們需要添加一個webpack.config.js
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"]
}
以上文件添加完成之后,我們可以在在命令行使用webpack
命令編譯生成這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>
在服務器端,我們需要修改Startup.cs
文件,在Configure
方法中添加靜態文件中間件和默認頁中間件,修改后最終的Configure
方法代碼如下
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMiddleware<GraphQLMiddleware>();
}
現在我們啟動項目,你將會看到如下圖所示的用戶界面。
在右側的Documentation Explorer面板中,你可以看到定義的所有query
, 並且可以了解到哪些字段是可用的,以及它們是干什么用的。
GraphiQL
提供了許多很棒的功能
- 語法高亮
- 編寫
GraphQL
查詢時,字段,參數,類型等的自動感知 - 實時錯誤高亮以及報告
- 自動補全查詢
- 可以在瀏覽器中模擬請求, 運行檢查查詢結果
本文源代碼:https://github.com/lamondlu/GraphQL_Blogs/tree/master/Part%20IV