DEV Community

loading...

Getting Vite, Vue 3 and Apollo Client 3 running

aisone profile image Aaron Gong Updated on ・2 min read

Assuming you have created a vite vue3 application.

Install packages

npm Install @apollo/client subscriptions-transport-ws graphql graphql-tag
Enter fullscreen mode Exit fullscreen mode

Edit vite.config.js

{
  ...
  optimizeDeps: {
    include: [
      ...
      '@apollo/client/core',
      '@apollo/client/cache',
      '@apollo/client/link/ws',
      '@apollo/client/link/context',
      '@apollo/client/utilities',
      ...
    ]
  },
  rollupInputOptions: { // ignore react stuff
    external: [
      'react'
    ]
  }
  ...
}
Enter fullscreen mode Exit fullscreen mode

GraphQL Initialization File

The file should look like this...

https://github.com/ais-one/vue-crud-x/blob/master/%40es-labs/esm/apollo.js

import { ApolloClient, HttpLink, split } from '@apollo/client/core'
import { InMemoryCache } from '@apollo/client/cache'
import { WebSocketLink } from '@apollo/client/link/ws'
import { setContext } from '@apollo/client/link/context'
import { getMainDefinition } from '@apollo/client/utilities'

const wsLink = new WebSocketLink({ // subscriptions-transport-ws package needs to be installed also
  uri: 'ws://127.0.0.1:3000/subscriptions',
  options: {
    reconnect: true
  }
})

// HTTP connexion to the API
const httpLink = new HttpLink({
  // You should use an absolute URL here
  // credentials: 'include', // UNCOMMENT FOR HTTPONLY_TOKEN
  uri: 'http://127.0.0.1:3000/graphql'
})

const link = split(
  // split based on operation type
  ({ query }) => {
    const { kind, operation } = getMainDefinition(query)
    return kind === 'OperationDefinition' && operation === 'subscription'
  },
  wsLink,
  httpLink
)

// REMOVE authLink FOR HTTPONLY_TOKEN
const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  // return the headers to the context so httpLink can read them
  let token = ''
  const item = localStorage.getItem('session') // survive a refresh
  if (item) {
    const user = JSON.parse(item)
    token = user.token
  }
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : '' // TBD - take into account refresh token and revocation
    }
  }
})

// Cache implementation
const cache = new InMemoryCache()

// Create the apollo client
export const apolloClient = new ApolloClient({
  link: authLink.concat(link), // REMOVE authLink FOR HTTPONLY_TOKEN
  cache,
  connectToDevTools: true,
  onError: ({ graphQLErrors, networkError }) => {
    if (networkError) console.log('networkError', networkError)
    if (graphQLErrors) {
      for (let err of graphQLErrors) {
        if (err.name === 'AuthenticationError') {
        }
        console.dir('graphQLErrors', err)
      }
    }
  }

})

Enter fullscreen mode Exit fullscreen mode

Working Example

You can find a working example in this project https://github.com/ais-one/vue-crud-x.

...

import apollo from '/lib/esm-rollup/apollo.js' // may not need to use provide/inject if no reactivity ? // served from express /esm static route
import { DO_HELLO } from '/src/queries.js'
apollo.init({ gwsUri: VITE_GWS_URI, gqlUri: VITE_GQL_URI })
const apolloClient = apollo.get()
if (apolloClient) {
  apolloClient // apollo test
    .query({
      query: DO_HELLO, // gql`query DoHello($message: String!) { hello(message: $message) }`,
      variables: {
        message: 'Meow'
      }
    })
    .then((data) => console.log('graphql', data))
    .catch((error) => console.error(error))
}
...
Enter fullscreen mode Exit fullscreen mode

run express server with graphql

cd vue-crud-x
cd example-app
npm i
npm i ../@es-labs/esm
npm i ../@es-labs/node
npm run knex -- development migrate
npm run knex -- development seed
npm run app -- development
Enter fullscreen mode Exit fullscreen mode

run vue vite application

cd vue-crud-x
cd example-vite
npm i
npm run dev
Enter fullscreen mode Exit fullscreen mode

You should see something like this in the console log

{data: {…}, loading: false, networkStatus: 7}
data: {hello: "Hello Meow"}
loading: false
networkStatus: 7
__proto__: Object
Enter fullscreen mode Exit fullscreen mode

I will try and update soonest possible as there are many things I am working on in the project and I am only one person. Please leave a comment here or issue on github. I try and check regularly if possible.

Discussion (2)

pic
Editor guide
Collapse
usman174 profile image
Muhmmad Usman

Absolutely informative, it would be great if u show an example with a vue 3 component with composition api. And the github link is deleted.

Collapse
aisone profile image
Aaron Gong Author • Edited

I just fixed the links in the article...