The use case of GraphQL in koa2 server

1, Create project

  • 1. Install some packages

    npm install koa --save
    npm install isodate --save
    npm install koa --save
    npm install koa-bodyparser --save
    npm install koa-router --save
    // Handling cross domain roles
    npm install koa2-cors --save
    npm install mongoose --save
    // These two are the syntax of ES6
    npm install babel-cli --save-dev
    npm install babel-preset-es2015 --save-dev
  • 2. Configure environment

    "scripts": {
        "test": "nodemon --exec babel-node --presets=es2015 app.js"
    },

2, Using mongoose in koa

  • 1. Create models layer
  • 2. Define view (view source code for data operations)

3, Using graphQl in koa

  • 1. Installation package

    npm install graphql graphql-server-koa --save
  • 2. Create a folder of graphql separately

  • 3. Generally, a table corresponds to a folder (including model, query, and mutation)

4, Using graphql to build a job model

  • 1. Code in model

    import {
      GraphQLObjectType,
      GraphQLInputObjectType,
      GraphQLString,
      GraphQLID
    } from 'graphql'
    
    
    export const jobType = new GraphQLObjectType({
      name: 'job',
      fields: {
        _id: {
          type: GraphQLID
        },
        job_name: {
          type: GraphQLString
        }
      }
    })
  • 2. Create a query statement file about job

    import {
      GraphQLID,
      GraphQLNonNull,
      GraphQLList
    } from 'graphql';
    
    import {
      jobType
    } from "./model";
    
    // Introduce data model
    import jobModel from './../../models/job';
    
    const Jobs = {
      type: new GraphQLList(jobType), // Return is an array
      args: {},
      async resolve(root, params, options) {
        const result = jobModel.find().exec();
        return result;
      }
    }
  • 3. Unified output in the project

    import {
      GraphQLObjectType,
      GraphQLSchema
    } from 'graphql';
    
    // Query and operation of introducing job
    import JobQueries from './job/query';
    import JobMutations from './job/mutation';
    
    
    export default new GraphQLSchema({
      query: new GraphQLObjectType({
        name: 'Queries',
        fields: Object.assign(
          JobQueries
        )
      }),
      mutation: new GraphQLObjectType({
        name: 'Mutations',
        fields: Object.assign(
          JobMutations
        )
      })
    })
  • 4. Similarly, if you want to use music, it's the same

  • 5. Configure routing

    import Router from 'koa-router';
    import {graphiqlKoa, graphqlKoa} from 'graphql-server-koa';
    import schema from "../graphql/schema";
    
    const router = new Router();
    
    router.get('/graphql', async (ctx, next) => {
      const result = await graphqlKoa({
        schema: schema
      })(ctx, next);
      console.log(result);
      ctx.body = result;
    })
    
    router.post('/graphql', async (ctx, next) => {
      await graphqlKoa({
        schema: schema
      })(ctx, next);
    })
    
    // This is only for easy viewing on the browser, and can be deleted after the project goes online
    router.get('/graphiql', async (ctx, next) => {
      await graphiqlKoa({
        endpointURL: '/graphql'
      })(ctx, next);
    })
    module.exports = router.routes();
  • 6. Summary

    • In graphql, there are only query and mutation
    • If it is a query statement, use query
    • If you want to add, delete or modify data, use music

5, Call the back-end data using graphql in the front-end (client-side) of React

  • 1. Install dependency package

    npm install react-apollo --save
    npm install apollo-client --save
    npm install apollo-link-http --save
    npm install apollo-cache-inmemory --save
    npm install graphql-tag --save
  • 2. The portal file configuration of react

    const client = new ApolloClient({
      link: new HttpLink('http://localhost:4000/graphql/'),
      cache: new InMemoryCache()
    });
    // Create a client as mentioned above
    ReactDOM.render(
      <ApolloProvider client={client}>
        <App />
      </ApolloProvider>, document.getElementById('root'));
    registerServiceWorker();
  • 3. Where data needs to be requested

    import React, { Component } from 'react';
    import { graphql } from 'react-apollo';
    import gql from 'graphql-tag';
    class Test01 extends Component{
      render(){
        return(
          <div>
            <h1>Hello</h1>
            <h2>{this.props.data.myField1}</h2>
          </div>
        )
      }
    }
    export default graphql(gql`
      query{
        Jobs{
          _id,
          job_name
        }
      }
    `)(Test01)

6, Use in vue

  • 1. Installation package

    npm install vue-graphql --save
  • 2. Create a graphql.js file

    import Vue from 'vue';
    import VueGraphQL from 'vue-graphql';
    Vue.use(VueGraphQL);
    const graphqlApi = 'http://localhost:4000/graphql/';
    const client = new VueGraphQL.Client(graphqlApi);
    export default client;
  • 3. Import in main.js

    import Vue from 'vue'
    import App from './App'
    import router from './router'
    import graphql from './graphql';
    Vue.config.productionTip = false
    
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      graphql,
      template: '<App/>',
      components: { App }
    })
  • 4. Using query statements

    ...
    mounted(){
        this.getGraphQlData();
    },
    methods: {
        getGraphQlData() {
          this.$graphql.request(`
              query{
                Jobs{
                  _id,
                  job_name
                }
              }
            `).then(result => {
            console.log(result);
          })
        }
    }
    ...
  • 5. Using mutations statements

    export default {
      name: 'HelloWorld',
      data () {
        return {
         job:'',
        }
      },
      methods: {
        postJob(){
          console.log(this.job);
          this.$graphql.request(`
              mutation{
                JobCreate(data:{job_name:"${this.job}"})
              }
            `).then(result => {
            console.log(result);
          })
        }
      }
    }

Seven. Source code download

Welcome to group chat, let's discuss the front-end technology stack

Group No.: 560285778

Tags: npm Vue React Mongoose

Posted on Fri, 01 May 2020 16:02:19 -0400 by tappy