GraphQL下一代API標(biāo)準(zhǔn)

GrapthQL介紹

  • GraphQL是Facebook開發(fā)的一種數(shù)據(jù)查詢語言,于2015年發(fā)布。
  • GraphQL是RESTful的升級(jí)版
  • GraphQL是用api(ajax請(qǐng)求)進(jìn)行數(shù)據(jù)庫查詢數(shù)據(jù)的玩意。

特點(diǎn)

  • 請(qǐng)求自己想要的數(shù)據(jù)字段
  • 多個(gè)資源,只用一次請(qǐng)求
  • 便于維護(hù)api

使用express與GraphQL開發(fā)一個(gè)HelloWorld

let express = require('express');
let graphqlHTTP =  require('express-graphql');//構(gòu)建graphql的中間件
let {buildSchema} = require('graphql');//核心庫

let schema = buildSchema(`
    type UserType{
        name:String
        age:Int
    }
    type Query{
        hello:String
        name:String
        user:UserType
    }
`);//定義查詢格式和類型

let rootValue = {
    hello:() => {
        return 'Hello World';//必須與hello的返回類型一樣
    },
    name(){
        return 'lh'
    },
    user(){
        return {
            name:'lh',
            age:21
        }
    }
};


let app = express();
app.listen(8000);

app.use('/graphql', graphqlHTTP(
    {
        schema,
        rootValue,
        graphiql:true//是否顯示開發(fā)界面,生產(chǎn)時(shí)建議不要為true
    }
));

參數(shù)類型與參數(shù)傳遞

類型

  • String:字符串
  • Int:整型
  • Float:小數(shù)
  • Boolean:布爾
  • ID:id類型不重復(fù)字符串
  • [類型]:數(shù)組類型

說明:類型可以自己定義

參數(shù)傳遞

...
let schema = buildSchema(`type Query {
    getUserName(id:String!):String
}`);
/*
    type Query為入口
    getUserName 通過id獲取用戶名
    并且id是字符型,并且不為空
*/
let rootValue = {
    getUserName({id}){
        let db = {
            1:'zhangs',
            2:'lis'
        };
        return db[id];
    }
}
...

瀏覽器中使用

fetch('/graphql', {
    method: "POST",
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
    body: JSON.stringify({
        query: `
            query GetUserName($id:String!){  //聲明變量
                getUserName(id:$id)  //使用變量
            }
        `,
        variables: {
            id:"1" //變量賦值
        }
    })
}).then(res => {
    console.log(res);
    
    return res.json()}).then(json=>{
    console.log(json);
    
});

輸入數(shù)據(jù)

...
let schema = buildSchema(`
input UserInput{
    name:String
    age:String
}

type User{
    name:String
    age:String
}

type Mutation{
    createUser(input:UserInput):User
    updateUser(id:ID!,input:UserInput):User
}

type Query {
    getUsers:[Users]
}`);
/*
    type Query為入口
*/
let db = {};
let rootValue = {
    createUser({input}){
        db[input.name] = input;
        return db[input.name];
    },
    updateUser({id,input}){
        Object.assign(db[id],db[id],input);
        return db[id];
    },
    getUsers(){
        let arr = [];
        for(const key in db){
            arr.push(db[key]);
        }
        return arr;
    }
}
...
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容