Note: This article is the basic knowledge of graphQL explained by me in the nestJS + GraphQL + Serverless training camp. It may be a bit different from before and after. The graphQL authorization mentioned in the article is also introduced in the next section

One, to the originalExpressreturnGraphqlProject changes

The code used in this chapter is the code for Express to return Graphql. Before using the code, basic configuration should be carried out, such as dealing with cross-domain problems. (Graphql essentially sends an HTTP request, so cross-domain problems naturally exist in the VUE project and need to be dealt with first.)

  • 1. Install cross-domain packages and configure middleware

    npm install cors
    Copy the code
    const cors = require('cors');
    // Process cross-domain requests
    app.use(cors());
    Copy the code
  • 2. Configure the middleware to fetch the request body

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

Second, invueIn the integrationGraphql

  • 1. Reference document address

  • 2. Install dependency packages

    npm install --save vue-apollo graphql apollo-boost graphql-tag
    Copy the code
  • 3, introduce apollo-boost module in SRC /main.js and instantiate ApolloClient

    import ApolloClient from 'apollo-boost'.const apolloClient = new ApolloClient({ 
      // You need to use absolute paths here, so there is no differentiation between environment development
      uri: 'http://localhost:8000/graphql'}); .Copy the code
  • 4. Configure vue-Apollo plugin in SRC /main.js

    import VueApollo from 'vue-apollo' 
    Vue.use(VueApollo);
    Copy the code
  • Create the Apollo Provider 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 absolute paths here
      uri: 'http://localhost:8000/graphql'});const apolloProvider = new VueApollo({
      defaultClient: apolloClient,
    })
    
    new Vue({
      render: h= > h(App),
      // Mount to the application
      apolloProvider,
    }).$mount('#app')
    Copy the code

Third, query data

  • 1. Use the Apollo page to query data

    According to the official description, simply mount apolloProvider to vue and add an additional attribute Apollo to vue’s hook function

    <template>
      <div class="about">
        {{accountList}}
      </div>
    </template>
    Copy the code
    import gql from 'graphql-tag';
    export default {
      name: 'About'.apollo: {
        accountList: gql`query { accountList { id username password } }`}},Copy the code

  • 2. Apollo uses functions to call

    import gql from 'graphql-tag';
    export default {
      apollo: {
        accountList () {
          return {
            query: gql`query { accountList{ id username password created_at } }`,}},}}Copy the code
  • 3. Click the button to get the data

    import gql from 'graphql-tag';
    // Define the schema for the query
    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); }})}}}Copy the code

    The above method can also be replaced by the following method. If the requested business is not complex, it can be written like this. If it is complex, a separate schema can be extracted 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); }})}...Copy the code
  • 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); }})}Copy the code

Fourth, improve the method of querying data

  • 1, the above method can query the data, but do not click the button repeatedly, otherwise there will be an error

  • 2, the improved version of the 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; })}Copy the code

Fifth, usemutationAdd data

  • See the specific implementation code below

    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 results', result);
        } else {
          // this.$message.error(' Please add data ')
          return false; }})}Copy the code

Six, optimizationGraphqlrequest

  • 1. Open the browser console and click requestGraphqlWhen you interface, you will find the following three parameters

  • 2. If the value of the same data or variables does not change, the request will not be made to the back end

  • 3,opertionNameWhat is it? I’m sure a lot of people are wondering, but if you look at these two pictures, I’m sure you won’t be wondering, right

    The operation name is the same as that used when you used query or mutation. This name can be used arbitrarily, and it is generally recommended that the operation name be the same as the API operation name on the backend.

    What’s the use of this operation name? We observe that all Graphql requests are sent with the same URL address. When we use traditional Restful apis, we need to obtain the address of the current request when we perform login authentication or obtain URL. For Graphql, this operation name is similar to this function, which API is used to distinguish the request.

Optimize your code

In the case of traditional Restful API requests, we tend to create a services folder in the project to keep API requests together for easy management, and rarely write requests to the VUE page. You can do the same in GraphQL, just in a different way.

  • 1. Create a GraphQL folder in your project to store Restful API like interface requests

  • 2, in the SRC/graphql/accountList) graphql create about query interface

    query AccountList {
      accountList {
        id
        username
        password
      }
    }
    Copy the code
  • 3. Introduced 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; }}...Copy the code
  • Vue cannot recognize graphQL files directly. We need to configure the loader to load GraphQL using Webpack

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

    module.exports = {
      configureWebpack: (config) = > {
        config.module.rules.push({
          test: /\.(graphql|gql)$/,
          exclude: /node_modules/,
          loader: 'graphql-tag/loader'})}};Copy the code
  • 6. Data processing is not refreshed

    Although initTableData was called, Graphql was not sent to the back end every time it added data, deleted data and modified data. This was because of the cache problem. The fields circled in red box needed to be added in the query so that data could be updated again every time it was called

    fetchPolicy: "no-cache".Copy the code

  • 7. Overall effect drawing of this chapter

  • 8. Code download address of this section