debian-mirror-gitlab/doc/development/fe_guide/graphql.md
2019-07-07 11:18:12 +05:30

3 KiB

GraphQL

We use Apollo and Vue Apollo for working with GraphQL on the frontend.

In order to use GraphQL, you need to enable the graphql feature flag, read more about Feature Flags.

Apollo Client

To save duplicated clients getting created in different apps, we have a default client that should be used. This setups the Apollo client with the correct URL and also sets the CSRF headers.

GraphQL Queries

To save query compilation at runtime, webpack can directly import .graphql files. This allows webpack to preprocess the query at compile time instead of the client doing compilation of queries.

Usage in Vue

To use Vue Apollo, import the Vue Apollo plugin as well as the default client. This should be created at the same point the Vue application is mounted.

import Vue from 'vue';
import VueApollo from 'vue-apollo';
import createDefaultClient from '~/lib/graphql';
Vue.use(VueApollo);

const apolloProvider = new VueApollo({
  defaultClient: createDefaultClient(),
});

new Vue({
  ...,
  apolloProvider,
  ...
});

Read more about Vue Apollo in the Vue Apollo documentation.

It is possible to use our Apollo setup with apollo-link-state by passing in a resolvers object when creating the default client. The default state can be set by writing to the cache after setting up the default client.

import Vue from 'vue';
import VueApollo from 'vue-apollo';
import createDefaultClient from '~/lib/graphql';
Vue.use(VueApollo);

const defaultClient = createDefaultClient({
  Query: {
    ...
  },
  Mutations: {
    ...
  },
});

defaultClient.cache.writeData({
  data: {
    isLoading: true,
  },
});

const apolloProvider = new VueApollo({
  defaultClient,
});

Testing

With Vue test utils it is easy to quickly test components that fetch GraphQL queries. The simplest way is to use shallowMount and then set the data on the component

it('tests apollo component', () => {
  const vm = shallowMount(App);

  vm.setData({
    ...mock data
  });
});

Usage outside of Vue

It is also possible to use GraphQL outside of Vue by directly importing and using the default client with queries.

import defaultClient from '~/lib/graphql';
import query from './query.graphql';

defaultClient.query(query)
  .then(result => console.log(result));

Read more about the Apollo client in the Apollo documentation.