Following the server project setup in the previous article, we begin the next phase of the client setup. This article mainly introduces the integration of Apollo-client and VUE using Vue-Apollo


Code warehouse

  • Client code
  • Server code

1. Introduction

What is the Apollo – client

Apollo-client is a client that integrates Vue, React, and other popular Graphql on the market.

What is a vue – Apollo

Vue-apollo integrates apollo-client into your VUE component with declarative queries. At the time of this writing, the plug-in is compatible with Vue2, while Vue3 is still under development.

2. Create a client project

vue create vue-graphql
cd vue-graphql
npm install --save vue-apollo graphql apollo-client apollo-link apollo-link-http apollo-cache-inmemory graphql-tag
// install the element UI and the Vue-router. // install the element UI and the Vue-router.
Copy the code
1. Install the plug-in
import VueApollo from 'vue-apollo'
Vue.use(VueApollo)
Copy the code
2. To createapollo-link-http
import { createHttpLink } from 'apollo-link-http';
const httpLink = createHttpLink({
    uri: 'http://localhost:3000/graphql'.// Specify the path of the backend application, which can be a function or a string. The default value is /graphql
});
Copy the code
3. Create aapollo-link
import { ApolloLink } from 'apollo-link';
const middlewareLink = new ApolloLink((operation, forward) = > {
    const token = localStorage.getItem('token'); // This is where the token is injected
    operation.setContext({
        headers: {
            Authorization: token || null}});return forward(operation);
});
Copy the code
4. Create the Apollo client
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloClient } from 'apollo-client';

const apolloClient = new ApolloClient({
    link: middlewareLink.concat(httpLink),
    cache: new InMemoryCache(),
    connectToDevTools: true
});
Copy the code
5. Create the Vue-apollo instance
import VueApollo from 'vue-apollo'

const apolloProvider = new VueApollo({
    defaultClient: apolloClient
})

new Vue({
  render: h= > h(App),
  router,
  apolloProvider // Inject into the vue instance
}).$mount('#app')
Copy the code

And register apolloProvide in the Vue instance.

new Vue({
  el: '#app'.// Inject apolloProvider like vue-Router or vuex. You can access the plugin instance via this.$Apollo
  apolloProvider,
  render: h= > h(App),
})
Copy the code
6. Vscode installationApollo GraphQL extension

Installing the vscode plug-in makes it easier for developers to develop Graphql applications. Its main functions are as follows:

  • Highlight the GraphQL syntax in the graphQL file and js file
  • Code intelligent tips, syntax optimization tips
  • Check syntax
  • More…..

Add an extension file for Apollo GraphQL to the root of your project

// apollo.config.js
module.exports = {
    client: {
        service: {
            name: 'my-app'.// The URL of the GraphQL API
            url: 'http://localhost:3000/graphql'
        },
        // Select the file to be processed by the extension
        includes: [
            'src/**/*.vue'.'src/**/*.js']}};Copy the code

After completing the above steps, we will be able to complete our basic development requirements.

Use 3.

1. Query

Server code

// src/cats/cats.graphql
type Query {
  cats: [Cat] // Batch querycat(id: ID!) : Cat// Single query
}
Copy the code
  @Query('cats') // Declare query. Corresponds to query in the graphQL file
  @UseGuards(CatsGuard) // This is a built-in nestjs annotation. Used for permission verification
  async getCats() {
    return this.catsService.findAll();
  }

  @Query('cat') // Declare query. Corresponds to query in the graphQL file
  async findOneById(
    @Args('id', ParseIntPipe)
    id: number,
  ): Promise<Cat> {
    return this.catsService.findOneById(id);
  }
Copy the code

Client code


<script>
import gql from 'graphql-tag';
export default {
    data() {
        return {
            cats: [].catList: []}},apollo: {
        // When the name of the query is the same as the name of the Apollo property
        cats: gql` query { cats { id, name, age } } `.// When the queried attribute name is inconsistent with the Apollo attribute name
        catList: {
            query: gql` query { cats { id, name, age } } `.update: (data) = > data.cats // How does vue-apollo process the data}}}; </script>Copy the code

Note: When the query attribute name is not the same as the query field, Vue-Apollo does not insert the returned data directly into the corresponding attribute name. Instead, we need to use the update attribute to handle this. As described in the code above.

Change in 2.
    methods: {
        createDataButtonClick() {
            this.addCat() // Call the mutation method
        },
        async addCat() {
            await this.$apollo.mutate({
                mutation: gql` mutation($createCatInput: CreateCatInput) { createCat(createCatInput: $createCatInput) { name, age } } `.variables: {
                    createCatInput: {
                        name: "cat2".age: 1}}}Copy the code
3. To subscribe to
1. Install the dependency
yarn add apollo-link-ws apollo-utilities subscriptions-transport-ws
Copy the code
2. Vue-apollo initialization modification
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws'
import { InMemoryCache } from 'apollo-cache-inmemory';
// import { ApolloLink } from 'apollo-link';
import { split } from 'apollo-link'
import { getMainDefinition } from 'apollo-utilities'


const httpLink = new HttpLink({
  uri: 'http://localhost:3000/graphql'.// For token verification, either headers or FETCH can be changed
})

// Create a subscribed WebSocket connection
const wsLink = new WebSocketLink({
  uri: 'ws://localhost:3000/subscriptions'.options: {
    reconnect: true,}})const link = split(
  // Divide by operation type
  ({ query }) = > {
    const definition = getMainDefinition(query)
    return definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
  },
  wsLink,
  httpLink
)

// Create the Apollo client
const apolloClient = new ApolloClient({
  // link: middlewareLink.concat(httpLink).concat(),
  link,
  cache: new InMemoryCache(),
  connectToDevTools: true
});

const apolloProvider = new VueApollo({
  defaultClient: apolloClient
})

new Vue({
  render: h= > h(App),
  router,
  apolloProvider
}).$mount('#app')
Copy the code
3. The server declares the subscription code

Subscriptions are primarily transmitted using WebSocket. The client registers the callback function, and the server registers and publishes the subscription.

// src/cats/cat.graphql
type Subscription {
  catCreated: Cat
}
Copy the code
// src/cats/cat.resolver.ts
import { PubSub } from 'graphql-subscriptions'; . @Mutation('createCat')
async create(@Args('createCatInput') args: CreateCatDto): Promise<Cat> {
    const createdCat = await this.catsService.create(args);
    pubSub.publish('catCreated', { catCreated: createdCat }); // Add a subscription
    returncreatedCat; }... @Subscription('catCreated')
catCreated() {
    return pubSub.asyncIterator('catCreated'); // Publish and subscribe
}
Copy the code

The article summary

  • Nest.js and GraphQL (part 1)