Uses and Benefits of GraphQL for your projects | Part 5

May 21, 2019

In our earlier installment on GraphQL, we hooked up our GraphQL server to an actual API in order to get real data. We had wrapped the TMDb API in a GraphQL server and verified if application can make calls for the data we need regarding movies, TV shows, genres etc. In this article we will create a client GraphQL app in Vue.js.
Lets make sure you have the Vue CLI tools installed:

$ npm install -g @vue/cli

We’ll need these Vue command line tools in order to generate a Vue project, as well as to add the GraphQL functionality.
Once you have the Vue CLI installed, let’s create our project. Run the following command:  

$ vue create web-graphql

When prompted, arrow down to the option “Manually select features” and hit Enter. This option will give us the ability to turn on many different features for our app, including TypeScript, Vuex, the Vue Router, and a number of other helpful things. Arrow down and press the space bar on each option in order to turn all of them on. Then hit Enter again.
Picture1

Sure, let’s turn on all of this stuff, why not?

Use class-style component syntax? Y
Use Babel alongside TypeScript for auto-detected polyfills? Y
Use history mode for router? (Requires proper server setup for index fallback in production) Y
Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): (Use arrow keys)
❯ SCSS/SASS
Pick a linter / formatter config: (Use arrow keys)
❯ TSLint 
Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
❯◉ Lint on save
Pick a unit testing solution: 
  Mocha + Chai 
❯ Jest 
Pick a E2E testing solution: 
  Cypress (Chrome only) 
❯ Nightwatch (Selenium-based) 
Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? (Use arrow keys)
❯ In dedicated config files
$ cd web-graphql/
$ npm run serve

The app will start and in Terminal it will display local and network URLs where you can access your app. Copy and paste the displayed URL into your browser (http://localhost:8080/ in my case).
You should now see the Vue “Hello World” page in your browser.
Picture2

Vue “Hello World” page

Let’s also install the Apollo client framework, which will enable our app to make GraphQL requests.

Go ahead and press Control-c in the Terminal to stop the Vue app.

Run:

$ vue add apollo
? Add example code Yes
? Add a GraphQL API Server? Yes
? Enable automatic mocking? Yes
? Add Apollo Engine? No

Should show something like this:

?  Invoking generator for vue-cli-plugin-apollo...
?  Installing additional dependencies...
added 8 packages from 9 contributors and audited 44141 packages in 13.489s
found 4 moderate severity vulnerabilities
  run `npm audit fix` to fix them, or `npm audit` for details
⚓  Running completion hooks...
✔  Successfully invoked generator for plugin: vue-cli-plugin-apollo
   The following files have been updated / added:
     .graphqlconfig.yml
     apollo-server/context.js
     apollo-server/directives.js
     apollo-server/mocks.js
     apollo-server/resolvers.js
     apollo-server/schema.graphql
     apollo-server/server.js
     apollo-server/type-defs.js
     apollo-server/utils/db.js
     apollo-server/utils/upload.js
     src/components/ApolloExample.vue
     src/graphql/AddMessage.gql
     src/graphql/FileFragment.gql
     src/graphql/Files.gql
     src/graphql/HelloWorld.gql
     src/graphql/MessageAdded.gql
     src/graphql/MessageFragment.gql
     src/graphql/Messages.gql
     src/graphql/UploadFile.gql
     src/vue-apollo.js
     vue.config.js
     .gitignore
     package-lock.json
     package.json
     src/main.ts

You should review these changes with git diff and commit them.

INFO  apollo Start the GraphQL API Server with npm run apollo
INFO  apollo Customize the mocks in apollo-server/mocks.js

Note that we now theoretically have a mock GraphQL server we can run to test against. Also, we have some GraphQL queries (the .gql files). We have a new Vue component, called ApolloExample, so that we can try our GraphQL queries. And we also have a file called vue-apollo, which contains the setup of the Apollo client for our Vue app.

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

While we’re at it, if you’re working in Visual Studio Code, let’s install a helpful plug-in for working with GraphQL, which can be found here:  https://marketplace.visualstudio.com/items?itemName=Prisma.vscode-graphql
Press Command-t to open a new Terminal tab in the same directory (~/Documents/_GraphQL/client/web-graphql for me). Let’s run the GraphQL server in this new tab:

$ npm run apollo

In this particular tab, it should show our GraphQL server running.
Picture3
Note that the URL for this server on my machine is http://localhost:4000/graphql. This URL is where we want to direct our GraphQL queries from our front-end Vue app.
Add the following compiler option to tsconfig.json in the “compilerOptions” list:

"noImplicitAny": false

Add the following to tslint.json under the “rules” object:

"semicolon": [true, "never"],
"space-before-function-paren": true

In router.js, we’ll need to add a new route so that the user can get to the ApolloExample.vue component. Add the following route to the routes array:

{
     path: '/apollo-example',
     name: 'apollo-example',
     component: () => import(/* webpackChunkName: "apollo" */ './views/Apollo.vue'),
   }

You may notice that we’ve referenced a new “page” in this route with “./views/Apollo.vue.” So let’s create that Apollo.vue file in the views folder (next to Home.vue and About.vue). That file will look like this:

<template>
<div class="apollo-example-page">
   <ApolloExample />
</div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import ApolloExample from '@/components/ApolloExample.vue'; // @ is an alias to /src
@Component({
 components: {
   ApolloExample
 },
})
export default class Apollo extends Vue {}
</script>

In App.vue, let’s modify our list of routes to include our new route:

<template>
<div id="app">
   <div id="nav">
     <router-link to="/">Home</router-link> |
     <router-link to="/about">About</router-link> |
     <router-link to="/apollo-example">Apollo Example</router-link>
   </div>
   <router-view/>
</div>
</template>

Let’s go back to the first tab and run the Vue app again:

$ npm run serve 

Now when you go to http://localhost:8080 and refresh the page, a link to the Apollo Example should show up in the list of links at the top of the page.
Picture4

New Apollo Example link shows at the top of the page

Click on the Apollo Example link to be taken to our new Apollo.vue component, which houses the ApolloExample.vue component with all of our GraphQL goodness.
Picture5

Our new Apollo.vue page

This ApolloExample.vue component contains many features that demonstrate the operation of a GraphQL client app, and you can see the server side of the equation in the “/apollo-server” folder, along with a folder called “/live” that contains our data as we interact with the page.

Trending Topics
Data & AI
Finance
Globant Experience
Healthcare & Life Sciences
Media & Entertainment
Salesforce

Subscribe to our newsletter

Receive the latests news, curated posts and highlights from us. We’ll never spam, we promise.

More From

Engineering Studio designs, builds, and evolves world-class digital end-to-end solutions. From human interfaces design to scalable platforms, our full-stack capabilities unleash better and more personalized customer experiences