Import GraphQL boot file to use in store action



  • Hi, I am using GraphQL, in Vue component it works fine with this.$apollo but I can’t find a way to use it in non vue component file.

    Boot file:

    const apolloProvider = createApolloClient();
    export default ({ app, Vue, ssrContext }) => {
      Vue.use(VueApollo);
      app.provide = { $apolloProvider: apolloProvider };
    
      if (ssrContext) {
        ssrContext.rendered = () => {
          ssrContext.apolloState = JSON.stringify(
            apolloProvider.defaultClient.extract()
          );
        };
      }
      return apolloProvider;
    };
    
    export { apolloProvider };
    

    Store action:

    import LoginRes from "../../graphql/login";
    import { apolloProvider } from "../../boot/apollo";
    
    export function getLoggedInUserInfo({ commit, payload }) {
      console.log(apolloProvider);
      apolloProvider
        .query({
          query: LoginRes.getUserByToken,
          variables: {
            token: payload
          }
        })
        .then(data => {
          commit("updateUser", data.data.getUserByToken);
        });
    }
    

    Error in console:

    client-entry.js?2f39:105 
    [Quasar] boot error: TypeError: _boot_apollo__WEBPACK_IMPORTED_MODULE_1__.apolloProvider.query is not a function
        at Store.getLoggedInUserInfo (actions.js?439d:6)
        at Array.wrappedActionHandler (vuex.esm.js?94e4:847)
        at Store.dispatch (vuex.esm.js?94e4:512)
        at Store.boundDispatch [as dispatch] (vuex.esm.js?94e4:402)
        at Array.__webpack_exports__.default (apollo.js?c149:72)
        at start (client-entry.js?2f39:88)
    


  • @tranmani said in Import GraphQL boot file to use in store action:

    console

    What is the output of console.log(apolloProvider) in the not store compared to the output in a vue file?



  • Do you really need vuex? vue-apollo comes with a caching system and using vuex is not needed and may be overhead. If you use chrome browser you can add the apollo extension to watch the cache. You can read https://apollo.vuejs.org/guide/local-state.html to find out more (att: v3 documentation, maybe you’re using one of the three v4 apis (Option API, Composition API, Component API) - setup is nearly the same (https://v4.apollo.vuejs.org/))



  • @dobbel said in Import GraphQL boot file to use in store action:

    @tranmani said in Import GraphQL boot file to use in store action:

    console

    What is the output of console.log(apolloProvider) in the not store compared to the output in a vue file?

    console log for actions file:

    actions.js?439d:5 
    ApolloProvider {clients: {…}, defaultClient: ApolloClient, defaultOptions: undefined, watchLoading: undefined, errorHandler: ƒ, …}
    ->
    clients: {defaultClient: ApolloClient}
    defaultClient: ApolloClient {defaultOptions: {…}, resetStoreCallbacks: Array(0), clearStoreCallbacks: Array(0), link: WebSocketLink, cache: InMemoryCache, …}
    defaultOptions: undefined
    errorHandler: errorHandler({ graphQLErrors, networkError }) { if (graphQLErrors) { graphQLErrors.map(({ message, locations, path }) => {…}
    prefetch: undefined
    watchLoading: undefined
    __proto__: Object
    

    console log of this.$apollo in .vue file

    DollarApollo {_apolloSubscriptions: Array(0), _watchers: Array(0), vm: VueComponent, queries: {…}, subscriptions: {…}, …}
    ->
    client: undefined
    error: undefined
    loadingKey: undefined
    queries: {}
    subscriptions: {}
    vm: VueComponent {_uid: 59, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
    _apolloSubscriptions: []
    _watchers: []
    data: (...)
    loading: (...)
    provider: (...)
    __proto__: Object
    

    @anli said in Import GraphQL boot file to use in store action:

    Do you really need vuex? vue-apollo comes with a caching system and using vuex is not needed and may be overhead. If you use chrome browser you can add the apollo extension to watch the cache. You can read https://apollo.vuejs.org/guide/local-state.html to find out more (att: v3 documentation, maybe you’re using one of the three v4 apis (Option API, Composition API, Component API) - setup is nearly the same (https://v4.apollo.vuejs.org/))

    I will have a look in to that



  • @tranmani This is how I set up the Apollo Client in quasar. This may not be “best practice”.

    My boot file: apolloclient.js

    import { ApolloClient } from 'apollo-client'
    import { InMemoryCache } from 'apollo-cache-inmemory'
    import VueApollo from 'vue-apollo'
    import fetch from 'node-fetch'
    import { createHttpLink } from 'apollo-link-http'
    // import { createUploadLink } from 'apollo-upload-client'
    
    const httpLink = createHttpLink({
      // uri: "http://localhost:4000/graphql",
      uri: `${process.env.API.BASE_URL}:${process.env.API.PORT}/graphql`,
      fetch: fetch
    })
    
    /* const uploadLink = createUploadLink({
      // uri: "http://localhost:4000/graphql",
      uri: `${process.env.API.BASE_URL}:${process.env.API.PORT}/graphql`,
      fetch: fetch
    }) */
    
    // Create the apollo client
    const apolloClient = new ApolloClient({
      link: httpLink,
      // link: uploadLink,
      cache: new InMemoryCache(),
      connectToDevTools: true,
      defaultOptions: {
        watchQuery: {
          fetchPolicy: 'cache-and-network',
          errorPolicy: 'ignore'
        },
        query: {
          fetchPolicy: 'network-only',
          errorPolicy: 'all'
        },
        mutate: {
          errorPolicy: 'all'
        }
      }
    })
    
    const apolloProvider = new VueApollo({
      defaultClient: apolloClient
    
      /* errorHandler({ graphQLErrors, networkError }) {
        if (graphQLErrors) {
          graphQLErrors.map(({ message, locations, path }) =>
            console.log(
              `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
            )
          );
        }
        if (networkError) {
          console.log(`[Network error]: ${networkError}`);
        }
      } */
    })
    
    export { apolloProvider }
    

    Then a typical store file start with

    import gql from 'graphql-tag'
    import { apolloProvider } from 'boot/apolloClient'
    import { Notify } from 'quasar'
    
    const gqlClient = apolloProvider.defaultClientde_text
    
    // typical action
    
    async allRecordings ({ commit }, payload) {
        console.log('action allRecordings', payload)
        commit('SET_IS_LOADING', 1)
        try {
          const response = await gqlClient.query({
            query: gql`
              query AllScheduledRecordings(
                $orderBy: [OrderByFields]
                $filterBy: [FilterByFields]
                $between: [BetweenFields]
                $whereIn: [WhereInField]
                $page: Page
              ) {
                allScheduledRecordings(
                  orderBy: $orderBy
                  filterBy: $filterBy
                  between: $between
                  whereIn: $whereIn
                  page: $page
                ) {
                  oid
                  name
                  channelOid
                  recurrenceOid
                  channelName
                  filename
                  status
                  startTimeLocal
                  endTimeLocal
                  failureReason
                  eventDetails
                  landscapeUrl
                  posterUrl
                  logoUrl
                  videoFiles {
                    name
                    base
                    dir
                    ext
                    baseURL
                  }
                }
              }
            `,
            variables: {
              ...payload
            }
          })
          console.log(response)
    
          commit('SET_RECORDINGS', response.data)
          commit('SET_IS_LOADING', -1)
        } catch (error) {
          Notify.create(`gqlClient action AllRecordings: ${error.message}`)
          console.error('gqlClient action AllRecordings: ', error)
          commit('SET_IS_LOADING', -1)
        }
      }
    

    Hope this is of some help. I am assuming you have the appropriate Apollo Client dependences.



  • @rhscjohn Thank you very much, I used your code as a reference and now it works, my boot file stays the same but my action file is now like this:

    import { apolloProvider } from "../../boot/apollo";
    import gql from "graphql-tag";
    
    const gqlClient = apolloProvider.defaultClient;
    
    export function getLoggedInUserInfo({ commit }, payload) {
      gqlClient
        .query({
          query: gql`
            query getUserByTokenList($token: String!) {
              getUserByToken(token: $token) {
                email
                firstname
                lastname
                bio
                note
                role
                coach
                club
                organization
                position
                players
              }
            }
          `,
          variables: {
            token: payload
          }
        })
        .then(data => {
          commit("updateUser", data.data.getUserByToken);
        });
    }
    

Log in to reply