GraphQL學習與實踐4(模擬客戶端請求)
在前面的學習中,使用的都是偏後臺,直接通過設置graphiql爲true,然後通過自帶的工具進行的驗證。這裏來說三個模擬客戶端請求的案例。
使用query的ajax請求
新建一個文件夾,test9-query目錄作爲該項模擬的根目錄。
新建schema目錄,schema.js文件:
const graphql = require('graphql');
const queryType = new graphql.GraphQLObjectType({
name: 'Query',
fields: {
greeting: {
type: graphql.GraphQLString,
resolve: () => 'Hello GraphQL From TutorialsPoint !!',
},
sayHello: {
type: graphql.GraphQLString,
args: {
name: {
type: graphql.GraphQLString
}
},
resolve: function (_, args) {
return `Hi ${args.name} GraphQL server says Hello to you!!`
}
}
}
});
這裏的schema.js文件中,就新建了一個Query的GraphQL的類型,裏面包含了greeting,sayHello兩個業務。
在根目錄新建server.js文件:
const express = require('express');
const cors = require('cors')
const graphqlHTTP = require('express-graphql');
const graphql = require('graphql');
const { queryType } = require("./schema/schema");
const schema = new graphql.GraphQLSchema({ query: queryType });
const app = express();
app.use(cors());
app.use('/graphql', graphqlHTTP({
schema: schema,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');
module.exports = { queryType };
根據之前的邏輯建立起一個服務。
注意:這裏較之前的代碼新加了一個cors模塊,用來處理服務端本地的跨域問題。需要安裝:
npm install --save cors
服務端ok之後,同樣可以使用自帶的工具進行驗證:
{
greeting,
sayHello(name:“test”)
}
如圖:
建立客戶端:
新建一個public文件夾,在該目錄下新建index.html文件:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function () {
$("#btnSayhello").click(function () {
const name = $("#txtName").val();
console.log(name);
$("#SayhelloDiv").html("loading....");
$.ajax({
url: "http://localhost:4000/graphql",
contentType: "application/json",
type: "POST",
data: JSON.stringify({
query: `{
sayHello(name:"${name}")}`
}),
success: function (result) {
console.log(JSON.stringify(result))
$("#SayhelloDiv").html("<h1>" + result.data.sayHello + "</h1>");
}
});
});
$("#btnGreet").click(function () {
$("#greetingDiv").html("loading....");
$.ajax({
url: "http://localhost:4000/graphql",
contentType: "application/json",
type: "POST",
dataType: 'json',
data: JSON.stringify({
query: `{greeting}`
}),
success: function (result) {
$("#greetingDiv").html("<h1>" + result.data.greeting + "</h1>");
}
});
});
});
</script>
</head>
<body>
<h1>Jquery Client </h1>
<hr />
<section>
<button id="btnGreet">Greet</button>
<br /> <br />
<div id="greetingDiv"> </div>
</section>
<br /> <br /> <br />
<hr />
<section>
Enter a name:<input id="txtName" type="text" value="kannan" />
<button id="btnSayhello">SayHello</button>
<div id="SayhelloDiv"> </div>
</section>
</body>
</html>
然後訪問該文件,點擊兩個按鈕,出現如圖所示效果:
服務端必須安裝一下cors模塊處理一下跨域的問題,不然就訪問不了,在本地的操作。
react中通過fetch網絡進行訪問
新建test10-react文件夾作爲該模擬的項目子根目錄。
新建react項目:
create-react-app hello-world-client
若是創建項目報not found的create-react-app的話,請自行安裝腳手架工具(Create React App是FaceBook的React團隊官方出的一個構建React單頁面應用的腳手架工具)。
npm install -g create-react-app
然後在hello-world-client目錄中,修改APP.js文件:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
async function loadGreeting() {
const response = await fetch('http://localhost:4000/graphql', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ query: '{greeting}' })
})
const rsponseBody = await response.json();
return rsponseBody.data.greeting;
console.log("end of function")
}
async function loadSayhello(name) {
const response = await fetch('http://localhost:4000/graphql', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ query: `{sayHello(name:"${name}")}` })
})
const rsponseBody = await response.json();
return rsponseBody.data.sayHello;
}
class App extends Component {
constructor(props) {
super(props);
this.state = { greetingMessage: '', sayHelloMessage: '', userName: '' }
this.updateName = this.updateName.bind(this);
this.showSayHelloMessage = this.showSayHelloMessage.bind(this);
this.showGreeting = this.showGreeting.bind(this);
}
showGreeting() {
loadGreeting().then(g => this.setState({ greetingMessage: g + " :-)" }))
}
showSayHelloMessage() {
const name = this.state.userName;
console.log(name)
loadSayhello(name).then(m => this.setState({ sayHelloMessage: m }))
}
updateName(event) {
this.setState({ userName: event.target.value })
}
componentDidMount() {
this.showGreeting();
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
<br />
<section>
showGreeting:{this.state.greetingMessage}
</section>
<br />
<section>
Enter a name:<input id="txtName" type="text" onChange={this.updateName}
value={this.state.userName} />
<button id="btnSayhello" onClick={this.showSayHelloMessage}>SayHello</button>
<br />
user name is:{this.state.userName} <br />
<div id="SayhelloDiv">
<h1>{this.state.sayHelloMessage}</h1>
</div>
</section>
</div>
);
}
}
export default App;
在上面的代碼中,分別封裝了loadSayhello和loadGreeting兩個方法進行範文graphql的服務,這個服務是上面test9-jquery中啓動的服務。在hello-world-client項目中啓動:
npm start
此時會自動打開默認的瀏覽器訪問3000端口,如端口被佔用,啓動的時候會自動詢問是否更換3001端口訪問的。如圖:
因爲啓動react客戶端是全屏的,爲了方便看點,這裏還修改了一下app.css:
.App {
text-align: center;
min-height: 100vh;
}
.App-logo {
height: 40vmin;
}
.App-header {
background-color: #282c34;
min-height: 90%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #09d3ac;
}
在react中使用Apollo客戶端
新建test11-apollo-react文件夾作爲該模擬的項目子根目錄。
新建server.js文件,這裏和上面的server.js文件是一樣的:
const express = require('express');
const cors = require('cors')
const graphqlHTTP = require('express-graphql');
const graphql = require('graphql');
const { queryType } = require("./schema/schema");
const schema = new graphql.GraphQLSchema({ query: queryType });
const app = express();
app.use(cors());
app.use('/graphql', graphqlHTTP({
schema: schema,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');
同樣的和上面的一樣的新建schema文件夾,裏面新建schema.js文件:
const graphql = require('graphql');
class Student {
constructor(id, firstName, lastName, college) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.college = college;
}
}
students = [new Student('id1', 'firstName1', 'lastName1', { name: 'test1' }),
new Student('id2', 'firstName2', 'lastName2', { name: 'test2' }),
new Student('id3', 'firstName3', 'lastName3', { name: 'test3' })];
const collegeType = new graphql.GraphQLObjectType({
name: 'College',
fields: {
id: {
type: graphql.GraphQLString
},
name: {
type: graphql.GraphQLString
},
location: {
type: graphql.GraphQLString
},
rating: {
type: graphql.GraphQLFloat
}
}
});
const studentType = new graphql.GraphQLObjectType({
name: 'Student',
fields: {
id: {
type: graphql.GraphQLString
},
firstName: {
type: graphql.GraphQLString
},
lastName: {
type: graphql.GraphQLString
},
college: {
type: collegeType
}
}
});
const queryType = new graphql.GraphQLObjectType({
name: 'Query',
fields: {
students: {
type: graphql.GraphQLList(studentType),
resolve: () => students,
}
}
});
module.exports = { queryType };
這裏就提供了students一個業務。
同樣的在子根目錄下創建react項目:
create-react-app hello-world-client
在hello-world-client目錄中,安裝客戶端的graphql庫以及Apollo Boost包:
npm install apollo-boost graphql
修改APP.js文件:
import React, {Component} from 'react';
// apollo client
import {ApolloClient, HttpLink, InMemoryCache} from 'apollo-boost'
import gql from 'graphql-tag'
const endPointUrl = 'http://localhost:4000/graphql'
const client = new ApolloClient({
link: new HttpLink({uri:endPointUrl}),
cache:new InMemoryCache()
});
async function loadStudentsAsync() {
const query = gql`
{
students{
id
firstName
lastName
college{
name
}
}
}
`
const {data} = await client.query({query}) ;
return data.students;
}
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
students:[]
}
this.studentTemplate = [];
}
async loadStudents() {
const studentData = await loadStudentsAsync();
this.setState({
students: studentData
})
console.log("loadStudents")
}
render() {
return(
<div>
<input type = "button" value = "loadStudents" onClick = {this.loadStudents.bind(this)}/>
<div>
<br/>
<hr/>
<table border = "3">
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>college Name</td>
</tr>
</thead>
<tbody>
{
this.state.students.map(s => {
return (
<tr key = {s.id}>
<td>
{s.firstName}
</td>
<td>
{s.lastName}
</td>
<td>
{s.college.name}
</td>
</tr>
)
})
}
</tbody>
</table>
</div>
</div>
)
}
}
通過上面我們可以看到,通過apollo-boost,使用其ApolloClient, HttpLink, InMemoryCache三個模塊。
ApolloClient:
使用Apollo Client,我們可以直接調用服務器而無需使用fetch API.此外,查詢和突變不應嵌入使用反向刻度表示法的字符串中,這是因爲, gql 函數直接解析查詢.這意味着,在GraphiQL工具中編寫查詢時,程序員可以以相同的方式直接編寫查詢。 gql 是一個標記函數,它將後面的刻度表示法中的模板字符串解析爲graphql查詢對象. Apollo Client查詢方法返回一個promise。
具體可以參考官網api解析:
https://www.apollographql.com/docs/react/api/apollo-client/
https://www.apollographql.com/docs/react/caching/cache-configuration/
項目圖如下:
更多
[GraphQL學習與實踐1(入門介紹)](https://blog.csdn.net/onsenOnly/artic
le/details/102639327)
GraphQL學習與實踐2(類型、傳參與構造函數類型)
GraphQL學習與實踐3(Mutations And Input Types)
GraphQL學習與實踐4(模擬客戶端請求)
GraphQL學習與實踐5(連接數據庫mongodb與mysql)
代碼:
onsenOnly:https://github.com/onsenOnly/graphql-test
有緣請點顆星,謝謝!