Example of implementing the Graphql interface in Vue

Example of implementing the Graphql interface in Vue

Note: This article is about the basic knowledge points of Graphql in the nestjs+graphql+serverless training camp that I am currently working on. It may not be connected to the previous and the next. The Graphql authorization mentioned in the article is also introduced in the next section.

1. Modify the original Express back to Graphql project

The code used in this chapter is the code that express returns to Graphql. Before using it, you need to perform basic configuration on the code, such as handling cross-domain issues (Graphql essentially sends an http request. Since this is the case, there are naturally cross-domain issues in the vue project, which need to be handled first)

1. Install cross-domain packages and configure middleware

npm install cors
const cors = require('cors');
// Handle cross-domain requests app.use(cors());

2. Configure the middleware to obtain the request body

// Process the request app.use(express.json()); //express.json=bodyParser.json
app.use(express.urlencoded({ extended: true }));

2. Integrate Graphql in Vue

1. Reference document address

2. Install dependency packages

npm install --save vue-apollo graphql apollo-boost graphql-tag

3. Introduce the apollo-boost module in src/main.js and instantiate ApolloClient

import ApolloClient from 'apollo-boost'
...
const apolloClient = new ApolloClient({ 
  // You need to use an absolute path here, no distinction is made between development environments uri: 'http://localhost:8000/graphql',
});
...

4. Configure the vue-apollo plug-in in src/main.js

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

5. Create an Apollo provider and mount it to the application

import Vue from 'vue'
import App from './App.vue'
import ApolloClient from 'apollo-boost'
import VueApollo from 'vue-apollo' 
Vue.use(VueApollo);

Vue.config.productionTip = false

const apolloClient = new ApolloClient({ 
  // You need to use the absolute path uri here: 'http://localhost:8000/graphql',
});
const apolloProvider = new VueApollo({
  defaultClient: apolloClient,
})

new Vue({
  render: h => h(App),
  // Mount to the application apolloProvider,
}).$mount('#app')

3. Query Data

1. Use the apollo page to query data

According to the official introduction, just mount apolloProvider to vue, and there will be an additional attribute apollo in the vue hook function

<template>
  <div class="about">
    {{accountList}}
  </div>
</template>

import gql from 'graphql-tag';
export default {
  name: 'About',
  apollo:
    accountList: gql`query {
      accountList {
        id
        username
        password
      }
    }`
  },
} 

2. Use functions to call in apollo

import gql from 'graphql-tag';
export default {
  apollo:
    accountList () {
      return {
        query: gql`query {
          accountList{ 
            id
            username
            password
            created_at
          }
        }`,
      }
    },
  }
}

3. Click the button to get data

import gql from 'graphql-tag';
// Define the query schema
const accountListGql = gql`{
  accountList {
    id
    username
    password
  }
}`;

export default {
  data() {
    return {
      tableList: [],
    }
  },
  methods: {
    getTableData() {
      this.$apollo.addSmartQuery('accountList', {
        query: accountListGql,
        result(response) {
          console.log(response);
          const {accountList} = response.data;
          this.tableList = accountList;
        },
        error(error) {
          console.log('Request failed', error);
        }
      })
    }
  }
}

The above method can also be replaced with the following writing method. If the requested business is not complicated, you can write it like this. If it is complicated, extract a schema separately according to the above method

...
getTableData() {
  this.$apollo.addSmartQuery('accountList', {
    query: gql`{
      accountList{
        id
        username
        password
      }
    }`,
    result(response) {
      console.log(response);
      const {accountList} = response.data;
      this.tableList = accountList;
    },
    error(error) {
      console.log('Request failed', error);
    }
  })
}
...

4. Request data by passing parameters

handleClick (rowData) {
  this.$apollo.addSmartQuery('account', {
    query: gql`
      query($id: ID!) {
        account(id: $id) {
          id
          username
          password
        }
      }
    `,
    variables: {
      id: rowData.id,
    },
    result (response) {
      console.log('Query single data', response.data);
    }
  })
}

4. Improvements to the data query method

1. The above method can query data, but you cannot click the button repeatedly, otherwise an error will occur

2. Improved version of query data, directly use the query method to query

getTableData () {
  this.$apollo.query({
    query: gql`{
      accountList{
        id
        username
        password
      }
    }`,
  }).then(response => {
    console.log(response);
    const { accountList } = response.data;
    this.tableList =accountList;
  })
}

5. Add data using mutation

See below for specific implementation code

onSubmit () {
  this.$refs.form.validate(async (valid) => {
    if (valid) {
      console.log(this.form);
      const result = await this.$apollo.mutate({
        mutation: gql`
          mutation addAccount($username: String!, $password: String!) {
            addAccount(username:$username,password: $password)
          }
        `,
        variables: {
          username: this.form.username,
          password: this.form.password,
        }
      });
      console.log('Update result', result);
    } else {
      // this.$message.error('Please add data')
      return false;
    }
  })
}

6. Optimizing Graphql Requests

1. When you open the browser console and click to request the Graphql interface, you will find the following three parameters

2. If the same data or the value of the variable does not change, no request will be made to the backend

3. What is operationName? I believe many people will have doubts. After seeing the following two pictures, I believe everyone will not be confused.

This operation name is the name you use when you use query or mutation. You can name it anything you want, but it is generally recommended to keep it consistent with the backend API operation name.
What is the use of this operation name? We observe that the requests sent by Graphql are all the same URL address. When we are using the traditional Restful API, we need to obtain the address of the current request when we do login authentication or obtain the URL. For Graphql, this operation name is similar to this function, which distinguishes which API is requesting.

7. Optimize code

In traditional Restful API requests, we prefer to create a services folder in the project to put all API requests together for easy management, and rarely write all requests to the Vue page. This can also be done in GraphQL, but in a different way.

1. Create a graphql folder in the project, which contains interface requests similar to the Restful API

2. Create a query interface in src/graphql/accountList.graphql

query AccountList {
  accountList {
    id
    username
    password
  }
}

3. Introduce in Vue

import AccountList from './../graphql/accountList.graphql';
...
methods: {
  async initTableData () {
    this.tableList = [];
    this.loading = true;
    const { data, loading } = await this.$apollo.query({
      query: AccountList,
    });
    console.log(data, 'request return data');
    this.loading = loading;
    this.tableList = data.accountList;
  },
}
...

4. If nothing unexpected happens, an error will be reported directly, because vue cannot directly recognize graphql files. We need to use webpack to configure the corresponding loader to load graphql

5. Create a vue.config.js configuration loader in the project root directory

module.exports = {
  configureWebpack: (config) => {
    config.module.rules.push({
      test: /\.(graphql|gql)$/,
      exclude: /node_modules/,
      loader: 'graphql-tag/loader'
    })
  },
};

6. Processing data is not refreshed

Each time we add, delete, or modify data, although we call initTableData, Graphql does not reach the backend. This is because of the cache problem. We need to add the fields circled in red when querying so that we can update the data every time we call it.

fetchPolicy: "no-cache", 

7. The overall effect diagram of this chapter

8. Code for this section Code download address

This is the end of this article about the implementation example of docking Graphql interface in Vue. For more relevant content about Vue docking Graphql interface, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Example code using GraphQL in Vue
  • Detailed explanation of how to use graphql, or vue-apollo, in vue-cli
  • Integrate graphql in vue project (vue-ApolloClient)

<<:  How to set mysql5.7 encoding set to utf8mb4

>>:  How to use a field in one table to update a field in another table in MySQL

Recommend

A brief discussion on the problem of Docker run container being in created state

In a recent problem, there is such a phenomenon: ...

2 reasons why html-css tag style setting does not work

1 CSS style without semicolon ";" 2 Tags...

The pitfalls of deploying Angular projects in Nginx

Searching online for methods to deploy Angular pr...

Linux sar command usage and code example analysis

1. CPU utilization sar -p (view all day) sar -u 1...

An analysis of div+float, a very important concept in website design

In website construction, you will always encounter...

A brief understanding of the three uses of standard SQL update statements

1. Environment: MySQL-5.0.41-win32 Windows XP Pro...

Vue3.0 implements the magnifying glass effect case study

The effect to be achieved is: fixed zoom in twice...

How to modify iTunes backup path under Windows

0. Preparation: • Close iTunes • Kill the service...

CSS naming conventions (rules) worth collecting Commonly used CSS naming rules

CSS naming conventions (rules) Commonly used CSS ...

Example code for mixing float and margin in CSS

In my recent studies, I found some layout exercis...

MySQL data analysis storage engine example explanation

Table of contents 1. Introduce cases 2. View the ...

Vue calls the PC camera to realize the photo function

This article example shares the specific code of ...

Front-end JavaScript operation principle

Table of contents 1. What is a JavaScript engine?...

Summary of Linux file directory management commands

touch Command It has two functions: one is to upd...