graphql 官網 鏈接,詳情翻閱官網,一定比我寫的好。
個人第一次接觸,公司大佬推薦,之後去搜文檔,教程,視頻。
入門Demo
必寫 hello world
const express = require('express');
const { buildSchema } = require('graphql');
const graphqlHttp = require('express-graphql');
const app = express()
const schema = buildSchema(`
type Query {
hello: String
}
`)
const root = {
hello: ()=>{
return 'hello world'
}
}
app.use('/graphql', graphqlHttp({
schema: schema,
rootValue: root,
graphiql: true // 調試工具
}))
app.listen(3000)
基本類型
String
Int
Float
Boolean
ID
[String]
const express = require("express");
const { buildSchema } = require("graphql");
const graphqlHttp = require("express-graphql");
const schema = buildSchema(`
type Query {
hello: String,
bookInfo: BookInfo,
booklist: [BookInfo]
},
type BookInfo {
name: String,
author: String,
}
`);
const root = {
hello: () => {
return "hello world";
},
Info: () => {
return {
name: "html",
author: "css",
};
},
list: () => {
return [
{
name: "js",
author: "js",
},
{
name: "html",
author: "html",
},
{
name: "css",
author: "css",
},
];
},
};
const app = express();
app.use(
"/graphql",
graphqlHttp({
schema: schema,
rootValue: root,
graphiql: true,
})
);
app.listen(3000);
參數傳遞
! 必傳
調試工具只識別 "
參數傳遞 解構 args { }
const express = require("express");
const { buildSchema } = require("graphql");
const graphqlHttp = require("express-graphql");
const schema = buildSchema(`
type Query {
hello: String,
Info: Info,
list: [Info],
currInfo(name: String!):Info
},
type Info {
name: String,
author: String,
}
`);
const root = {
hello: () => {
return "hello world";
},
Info: () => {
return {
name: "html",
author: "css",
};
},
list: () => {
return [
{
name: "js",
author: "js",
},
{
name: "html",
author: "html",
},
{
name: "css",
author: "css",
},
];
},
currInfo({name}){
const list = [
{
"name": "js",
"author": "js"
},
{
"name": "html",
"author": "html"
},
{
"name": "css",
"author": "css"
}
];
let result = list.filter(item => item.name == name )
return result[0]
}
};
const app = express();
app.use(
"/graphql",
graphqlHttp({
schema: schema,
rootValue: root,
graphiql: true,
})
);
app.listen(3000);
客戶端傳遞
新建index.html
你可以單獨出來(注意跨域),也可以public express.static
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const name = "js"
const query = `query CurrInfo($name:String !){ // query 後面接口名字隨意,就像我們平時自定義封裝接口重新取名一樣,但爲了語義化
currInfo(name: $name){ // $name 個人理解爲形參 name是$name賦值的對象
name, // 要指定返回的字段
author
}
}`;
fetch('http://localhost:3000/graphql',{
method:"POST",
headers:{
'Content-type':'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
query,
variables: {name}
})
}).then( res => console.log(res))
</script>
</body>
</html>
mutation
const express = require("express");
const { buildSchema } = require("graphql");
const graphqlHttp = require("express-graphql");
const schema = buildSchema(`
input AccountInput {
name: String
age:Int
sex:String
department: String
}
type Account {
name: String
age:Int
sex:String
department: String
}
type Mutation {
createAccount(input: AccountInput): Account
updateAccount(name: ID!,input: AccountInput): Account
},
type Query {
accounts: [ Account ]
}
`);
let db = [];
const root = {
accounts() {
return db;
},
createAccount({ input }) {
db.push(input);
return input;
},
updateAccount({ name, input }) {
const item = db.filter((item) => item.name == name);
if (item) {
const updateAccount = Object.assign({}, item, input);
db = db.map((item) => {
return item.name === updateAccount.name ? updateAccount : item;
});
return updateAccount;
}
},
};
const app = express();
app.all("*", function (req, res, next) {
// 設置請求頭爲允許跨域
res.header("Access-Control-Allow-Origin", "*");
// 設置服務器支持的所有頭信息字段
res.header(
"Access-Control-Allow-Headers",
"Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild, sessionToken"
);
// 設置服務器支持的所有跨域請求的方法
res.header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
if (req.method.toLowerCase() == "options") {
res.send(200); // 讓options嘗試請求快速結束
} else {
next();
}
});
app.use(
"/graphql",
graphqlHttp({
schema: schema,
rootValue: root,
graphiql: true,
})
);
app.listen(3000);
以創建爲例 客戶端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var name = "html5"
var age = 1
var sex = "man"
var department ="html"
var query = `mutation CreateAccount($input: AccountInput){
createAccount(input: $input){
name,
age,
sex,
department
}
}`;
fetch('http://localhost:3000/graphql',{
method:"POST",
headers:{
'Content-type':'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
query,
variables: {
input: {
name,
age,
sex,
department
}}
})
}).then( res => console.log(res))
</script>
</body>
</html>
入門就先這樣啦 睡覺