vue 如何使用graphql? node.js如何使用graphql? node框架 egg 如何使用graphql?

說明   本文中 vue+node 均基於的 apollo.js 使用   vue 是在apollo基礎上 封裝了一個 vue的組件  方便使用

 

vue 使用 graphql

1 下載依賴包

npm install --save vue-apollo graphql apollo-client apollo-link apollo-link-http apollo-cache-inmemory graphql-tag


2 以 vue 腳手架 項目結構爲例  

一

在 src/views/mains 裏進行配置

import VueApollo from 'vue-apollo'
Vue.use(VueApollo)

然後 引入自己一會 要寫的 vueApollo的二次封裝的配置文件
import apolloProvider from './vueApollo'

然後 最後 new Vue時 引入他
new Vue({
  el: '#app',
  provide: apolloProvider.provide(),
  router,
  store,
  i18n,
  render: h => h(App)
})

二

然後相對路徑 創建 vueApollo.js


內部代碼如下

import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import VueApollo from 'vue-apollo'
const httpLink = new HttpLink({
  uri: '/v1/graphql',
  /* 其中./v1是我在vue的config中配置時解決跨域時起的代理一個名字,後面的是後端
 暴露接口方法的地址 */
  credentials: 'same-origin'
  /* 這個屬性的意思是在同源的情況下攜帶cookie,因爲vue-apollo本身發送的是一個fetch請求,所以在發送請求時不會自動攜帶cookie,所以我們需要加上此屬性 */
})
const apolloClient = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache(),
  connectToDevTools: true
})
export default new VueApollo({
  defaultClient: apolloClient,
  clients: { default: apolloClient }
})


3 使用 vue-apollo 

先看結構圖

下面是vue頁面的全部代碼

<template>
  <div class="app-container documentation-container" style="overflow: auto;-webkit-overflow-scrolling: touch; height: calc(100vh - 84px);">
    <h1>查詢</h1>
    <div class="divItem">
      <button @click="getInfo"> query Test 獲取數據</button>
      <span style="margin-left: 50px">結果:<span style="color: red">{{test1Res}}</span></span>
    </div>
    <div class="divItem">
      <button @click="getInfo2"> query login 用戶名密碼 獲取數據</button>
      <span style="margin-left: 50px">結果:<span style="color: red">{{test2Res}}</span></span>
    </div>
    <div class="divItem">
      <button @click="getInfo3"> query login 模型 獲取數據</button>
      <span style="margin-left: 50px">結果:<span style="color: red">{{test3Res}}</span></span>
    </div>
    <div class="divItem">
      <span>輸入id</span><input type="text" v-model="userId">
      <button @click="getInfo4"> query getUserInfo 獲取數據</button>
      <span style="margin-left: 50px">結果:<span style="color: red">{{test4Res}}</span></span>
    </div>
    <div class="divItem">
      <span>輸入id</span><input type="text" v-model="userId">
      <span>輸入vip</span><input type="text" v-model="vip">
      <button @click="getInfo5"> query getUserShowVip 獲取數據</button>
      <span style="margin-left: 50px">結果:<span style="color: red">{{test5Res}}</span></span>
    </div>
    <div class="divItem">
      <span>輸入vip</span><input type="text" v-model="vip">
      <button @click="getInfo6"> query queryUsers 獲取數據</button>
      <span style="margin-left: 50px">結果:<span style="color: red">{{test6Res}}</span></span>
    </div>
    <div style="border-bottom: 1px solid red"></div>
    <h3>修改</h3>
    <div class="divItem">
      <span>輸入name</span><input type="text" v-model="username">
      <span>輸入頭像</span><input type="text" v-model="userAvatar">
      <span>輸入vip</span><input type="text" v-model="vip">
      <button @click="getInfo7"> mutation 添加數據</button>
      <span style="margin-left: 50px">結果:<span style="color: red">{{test7Res}}</span></span>
    </div>
  </div>
</template>
<script>
import test1 from './gql/test1'
import test2 from './gql/test2'
export default {
  name: 'Documentation',
  data() {
    return {
      test1Res: '',
      test2Res: '',
      test3Res: '',
      userId: '',
      test4Res: '',
      vip: '',
      test5Res: '',
      test6Res: '',
      username: '',
      userAvatar: '',
      test7Res: ''
    }
  },
  created: function() {
  },
  methods: {
    getInfo() {
      this.$apollo.query({
        query: test1.testQuery
      }).then((res) => {
        const { test } = res.data
        this.test1Res = test
      })
    },
    getInfo2() {
      const variables = {
        username: 'gq',
        pwd: '123'
      }
      this.$apollo.query({
        query: test1.testLogin,
        variables
      }).then((res) => {
        const { login } = res.data
        this.test2Res = login
      })
    },
    getInfo3() {
      const variables = {
        loginModel: {
          username: 'gq',
          pwd: '123',
          authCode: '321'
        }
      }
      this.$apollo.query({
        query: test1.testLogin_m,
        variables
      }).then((res) => {
        const { login_m } = res.data
        this.test3Res = login_m
      })
    },
    getInfo4() {
      const variables = {
        userid: this.userId
      }
      this.$apollo.query({
        query: test1.getUserInfo,
        variables
      }).then((res) => {
        const { getUserInfo } = res.data
        this.test4Res = getUserInfo
      })
    },
    getInfo5() {
      const variables = {
        userid: this.userId,
        vip: parseInt(this.vip)
      }
      this.$apollo.query({
        query: test1.getUserShowVip,
        variables
      }).then((res) => {
        const { getUserShowVip } = res.data
        this.test5Res = getUserShowVip
      })
    },
    getInfo6() {
      const variables = {
        vip: parseInt(this.vip)
      }
      this.$apollo.query({
        query: test1.queryUsers,
        variables
      }).then((res) => {
        const { queryUsers } = res.data
        this.test6Res = queryUsers
      })
    },
    getInfo7() {
      const variables = {
        vip: parseInt(this.vip),
        name: this.username,
        userAvatar: this.userAvatar
      }
      this.$apollo.mutate({
        mutation: test2.testCreateUser,
        variables
      }).then((res) => {
        const { createUser } = res.data
        this.test7Res = createUser
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .divItem{
    margin-top: 30px;
  }
  .documentation-container {
    background-color: #F9FAFB;
    .document-btn {
      float: left;
      margin-left: 50px;
      display: block;
      cursor: pointer;
      background: black;
      color: white;
      height: 60px;
      width: 200px;
      line-height: 60px;
      font-size: 20px;
      text-align: center;
    }
    /deep/.md-bill-detail{
      padding-bottom: 0!important;
    }

    /deep/.md-detail-item{
      font-size: 14px!important;
      padding-top: 3px!important;
      padding-bottom: 3px!important;
    }
    /deep/.md-example-child  header:nth-child(2){
      display: none!important;
    }
    /deep/.md-bill-neck{
      margin: 0 24px;
    }
    .md-bill{
      background-color: #ffffff;
    }
    /deep/.md-bill-header{
      padding: 28px 32px 0;
    }
    .m20{
      margin-top: 20px;
    }
    /* .md-water-mark{
       overflow: visible;
       .md-bill-neck :before,:after{
       content: '';
       position: absolute;
       top: 0;
       width: 36px;
       height: 36px;
       border-radius: 18px;
       background-color: #F3F4F5;
     }}*/
    /deep/.md-bill-neck :before{
      content: '';
      position: absolute;
      top: -11px;
      width: 22px;
      height: 22px;
      border-radius: 11px;
      background-color: #F3F4F5;
      left: -44px;
    }
    /deep/.md-bill-neck :after{
      content: '';
      position: absolute;
      top: -11px;
      width: 22px;
      height: 22px;
      border-radius: 11px;
      background-color: #F3F4F5;
      right: -44px;
    }
    /deep/ .md-example-child{
      margin-bottom: 20px;
    }
  }
</style>

上面代碼中 調用方法是 

this.$apollo.query 和  this.$apollo.mutate

而我們標準的 gql語言 在 相對的2個文件夾裏  

展示一個看看   這裏要引入   graphql-tag  然後用gql 報過我們的語句即可  剩下的就是配合後臺的 gql了

下面是test1

import gql from 'graphql-tag' // 引入graphql
export default {
  testQuery: gql `query Query{  
    test
  }`,
  testLogin: gql `query login($username:String!,$pwd:String!){
    login(username:$username,pwd:$pwd){
       status
       errorCode
       msg
    }
  }`,
  testLogin_m: gql `query testLogin_m($loginModel: LoginModel!){
    login_m(loginModel:$loginModel){
       status
       errorCode
       msg
    }
  }`,
  getUserInfo: gql `query getUserInfo($userid: ID!){
    getUserInfo(userid:$userid){
       id
       name
       userAvatar
       vip
       showVip
       token
       fans {
        name
       }
    }
  }`,
  getUserShowVip: gql `query ($userid: ID!,$vip:Int){
    getUserShowVip(userid:$userid,vip:$vip){
       id
       name
       userAvatar
       vip
       showVip
       token
       fans {
        name
       }
    }
  }`,
  queryUsers: gql `query queryUsers($vip:Int!){
    queryUsers(vip:$vip){
       name
       fans {
         name
         vip
         token
       }
    }
  }`
}

把 test2 也奉上

import gql from 'graphql-tag'
export default {
  testCreateUser: gql`mutation createUser($name:String,$userAvatar:String,$vip:Int){
    createUser(name:$name,userAvatar:$userAvatar,vip:$vip){
      errorCode
      status
      msg
    }
  }`
}

================================分割線=========================================

下面說一下 node端 如何是用 apollo   我用的是egg框架  

1 下載依賴 

npm install -S  apollo-boost  node-fetch graphql-tag

直接在controller 的base裏  引入

// import ApolloClient from 'apollo-boost';
const Apollo = require('apollo-boost')
const fetch = require('node-fetch')
// import { HttpLink } from 'apollo-link-http';
// import { InMemoryCache } from 'apollo-cache-inmemory';
const httpLink = new Apollo.HttpLink({
  uri: 'http://192.168.50.82:7002/graphql',
  fetch:fetch,
  /* 其中./v1是我在vue的config中配置時解決跨域時起的代理一個名字,後面的是後端
 暴露接口方法的地址 */
  credentials: 'same-origin',
  /* 這個屬性的意思是在同源的情況下攜帶cookie,因爲vue-apollo本身發送的是一個fetch請求,所以在發送請求時不會自動攜帶cookie,所以我們需要加上此屬性 */
});
const apolloClient = new Apollo.ApolloClient({
  link: httpLink,
  cache: new Apollo.InMemoryCache(),
  connectToDevTools: true,
});

註釋的部分 是樓主第一次嘗試的時候寫的  後來就引入 這2個就夠了

然後定義2個 base方法 一個query  一個  mutation

 

async gqlQuery(config) {
    const res = await apolloClient.query(config)
    return res.data
  }

  async gqlMutation(config) {
   const res = await apolloClient.mutate(config)
   return res.data
  }

然後 引入 gql    

const gql = require('graphql-tag')
//獲取首頁數據
        // console.info('*************11111111***************')
        // const testQuery = gql `query Query{
        //   test
        // }`
        // const r1 = await this.gqlQuery({
        //     query:testQuery
        // })
        // console.info(r1)
        // console.info('*************22222222***************')

        // console.info('*************11111111***************')
        // const testLogin = gql `query login($username:String!,$pwd:String!){
        //     login(username:$username,pwd:$pwd){
        //        status
        //        errorCode
        //        msg
        //     }
        // }`
        // const variables = {
        //     username:'gq',
        //     pwd:'123'
        // }
        // const r1 = await this.gqlQuery({
        //     query:testLogin,
        //     variables
        // })
        // console.info(r1)
        // console.info('*************22222222***************')

        const testCreateUser = gql`mutation createUser($name:String,$userAvatar:String,$vip:Int){
            createUser(name:$name,userAvatar:$userAvatar,vip:$vip){
              errorCode
              status
              msg
            }
        }`
        const variables = {
            vip:1,
            name:'1',
            userAvatar:'1',
        }
        const r3 = await this.gqlMutation({
            mutation: testCreateUser,
            variables
        })

大功告成  完結

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章