Activities

drewbaker

drewbaker posted a new feature request

apollo-module •

idea wssLinkOptions for subscriptions?

What problem does this feature solve?

Currently we have httpLinkOptions but we don't have the same options for the a wsLink setup.

What does the proposed changes look like?

Would be great f my config could look like this:

clientConfigs: {
    default: {
        wsEndpoint: "wss://localhost:4000",
        wsLinkOptions: {
            reconnect: true,
            lazy: true,
            connectionParams() {
                workspaceId: "",
                token: ""
            }
        }
    }
}
gibkigonzo

gibkigonzo posted a new question

apollo-module •

setting custom http link

Hello, I'm trying to use custom http link and I get error.
Here is my config:

  apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: 'https://some-test-uri.prismic.io/graphql',
        link: PrismicLink({
          uri: 'https://some-test-uri.prismic.io/graphql',
        }),
        defaultHttpLink: false
      }
    }
  },

Error: Cannot read property 'length' of undefined

    }
    return LinkError;
}(Error));
exports.LinkError = LinkError;
function isTerminating(link) {
    return link.request.length <= 1; // here is error
}
exports.isTerminating = isTerminating;
function toPromise(observable) {
    var completed = false;
    return new Promise(function (resolve, reject) {

PrismicLink returns proper format (I guess):

ApolloLink {
  request: [Function]
}

What I'm doing wrong?

vana-dev

vana-dev posted a new bug report

apollo-module •

bug nuxtServerInit error

Version

v4.0.0-rc.19

Steps to reproduce

I don't know what is wrong :/ I tried to get data in nuxtServerInit

this is my store/index.js

import headerMenuGql from "~/gql/headerMenu.gql";

export const state = () => ({
  headerMenu: null
})

export const mutations = {
  setHeaderMenu (state, data) {
    state.headerMenu = data
  },
}

export const actions = {
  async nuxtServerInit({ dispatch }) {
    await dispatch('getHeaderMenu')
  },
  async getHeaderMenu ({ commit }) {
    const response = await this.app.apolloProvider.defaultClient.query({query: headerMenuGql})
    commit('setHeaderMenu', response)
  }
}

and headerMenu.gql

query headerMenu {
  menus {
    nodes {
      name
      slug
      menuItems {
        nodes {
          childItems {
            nodes {
              menuItemId
              label
              url
            }
          }
          menuItemId
          label
          url
        }
      }
      menuId
    }
  }
}

What is expected ?

get data into vuex store

What is actually happening?

GraphQL error: Internal server error

lsliwaradioluz

lsliwaradioluz posted a new question

apollo-module •

How to use smart queries and mimic behaviour of asyncData?

I dug through all issues regarding smart queries and their cooperation (or lack thereof) with server-side-rendering but none of the answers provided really hits the mark.

In my SSR Nuxt app, I need to fetch some data from an external API created with Strapi. If I understood correctly, this can be achieved in two ways:

  • either using the asyncData method and calling client.query in it
  • or using Apollo's Smart Query declared in the apollo definition

The former works like a charm. When you navigate to the next page using <nuxt-link>, the router waits for the asyncData to load everything and only when the data is ready, it loads that next page. Hence the white progress bar on top of the screen:

https://www.loom.com/share/4513b5ff0b6e40e6bc220364fc190c1c

However, the problem with this solution is that the query run from asyncData does not update automatically when I commit a mutation and the cache changes. That's why I turned to using Smart Queries which cause no such problems.

Unfortunately, those Smart Queries do not seem to be suited for SSR at all. After navigating to a page that uses one of them, my app throws an error (Cannot read property 'length' of undefined). I know, Smart Query is executed on the client so I used v-if="!$apollo.loading" on the root element in template and the error is gone. However, right now I can observe another strange behaviour after navigating to the next page using <nuxt-link>:

https://www.loom.com/share/6d403cc0a1a5485ca48dee1177b29405

The next page gets loaded but is empty (due to v-if used on root element in template). The content appears after a while, once the SmartQuery is completed.

  • is there any way to make router wait for the result of SmartQuery once we hit nuxt-link? Just like it happens in case of using asyncData? This question has already been asked in #278 but no one answered
  • if not, is there any other way to make Smart Query behave like asyncData? Or maybe we could use both - asyncData to fetch data initially and then Smart Query to watch for cache changes and update component accordingly? Or maybe we should use asyncData but instead of client.query use client.watchQuery? I tried this one but could not make watchQuery fetch Data on initial load - just like regular query does
  • if none of the above, what could we do to improve UX and get rid of that blank page for 1-2 seconds? Load some placeholders like faded rectangles ? Or maybe create some custom progress bar?

Thank you in advance,
Łukasz

Billybobbonnet

Billybobbonnet posted a new feature request

apollo-module •

idea Use Apollo Nuxt Modeule with AWS Amplify (appsync) API

What problem does this feature solve?

I tried to stick with this module when working with a GraphQL AWS API. I couldn't configure how to attach to the request headers the requested API key.

When "edit and resend" the request to add ''x-api-key" as key with the related key as value, it works. See https://stackoverflow.com/q/60816883/3793161

What does the proposed changes look like?

If it is already possible, it's a feature request for the readme. If not, it does not look like a big leap to allow the addition of custom headers for cases like this.

lennartkerkvliet

lennartkerkvliet posted a new question

apollo-module •

Error handling not using Observable

I'm trying to write code for error handling so that I could use JWT refresh tokens. The docs/README provide this example for error handling.

// plugins/apollo-error-handler.js
export default ({ graphQLErrors, networkError, operation, forward }, nuxtContext) => {
  console.log('Global error handler')
  console.log(graphQLErrors, networkError, operation, forward)
}

What I would expect is that I could use operation and forward to write return forward(operation) to retry a failed request, but unfortunately both are undefined. I would also expect that as for example the docs for the apollo-link-error show, you could return an Observable (from "apollo-link") so that you would be able to retry a request. Creating a new Observable will also not result in anything

This is the code I have written:

import { Observable } from 'apollo-link'

export default ({ graphQLErrors, networkError, operation, forward }, nuxtContext) => {
    if (graphQLErrors) {
        for (let err of graphQLErrors) {
            switch (err.extensions.code) {
                case 'UNAUTHENTICATED':
                    return new Observable(subscriber => {

                        nuxtContext.store.dispatch('refresh').then(() => {
                            if (subscriber.closed) return;

                            return forward(operation)subscribe(subscriber);
                        }).catch(error => {
                            subscriber.error(error)
                        })
                    })
            }
        }
    }
};

Everything contained inside Observable is never executed and operation and forward are undefined. Is this a bug? And if it is not, are there any workarounds?

lopermo

lopermo posted a new bug report

apollo-module •

bug Custom error handling not firing

Version

v4.0.0-rc.19

Reproduction link

https://jsfiddle.net/

Steps to reproduce

Add option to nuxt.config.js -> errorHandler: '~/plugins/apollo-error-handler.js',
Create file and print error.

What is expected ?

It should print errors on the console

What is actually happening?

It doesn't print anything when an error happens.

Additional comments?

I'm trying to catch errors when the connection to the server is lost and there's a subscription ongoing. But I can't even catch and log when the server isn't connected and I try to run a query. It's like if the file in "errorHandler" option is ignored.

humiyan02

humiyan02 posted a new question

apollo-module •

onLogin error with Cognito

I used ID token of Cognito user in onLogin method.

      await this.$apolloHelpers.onLogin(state.user.signInUserSession.idToken.jwtToken, undefined, {
        expires: 7,
        path: '/'
      })

But error occurred bellow.
Error on cache reset (setToken) Network error: Response not successful: Received status code 401

When I try putting ID token into getAuth in plugin, It success.

  return {
    httpEndpoint:
      'https://aaaaaaaaaaaaaaaaaa.appsync-api.ap-northeast-1.amazonaws.com/graphql',
    getAuth: () => idToken
  }
}
kicaal

kicaal posted a new question

apollo-module •

can't connect to chrome apollo dev tools

Reference --> https://github.com/nuxt-community/apollo-module/issues/7

it seems that this is broken again :(

drewbaker

drewbaker posted a new bug report

apollo-module •

bug Cookies not sent in SSR mode

Version

v4.0.0-rc.19

Reproduction link

https://pyj86.sse.codesandbox.io

Steps to reproduce

If httpLinkOptions.credentials = true it seems the Cookie header is set when client side, but not when the SSR request is happening.

Setup nuxt.config.js like so:

    apollo: {
        authenticationType: "Basic",
        clientConfigs: {
            default: "~/plugins/apollo-config-default.js"
        }
    }

And then in apollo-config-default.js

export default function() {
    return {
        httpEndpoint: process.env.DEFAULT_ENDPOINT,
        getAuth: () => process.env.BASIC_API_TOKEN || "",
        httpLinkOptions: {
            credentials: "include"
        }
    }
}

Hard load to a public URL, like: https://pyj86.sse.codesandbox.io/

It works fine, browse to a private URL via a nuxt-link and it works fine.

Hard load into a private URL and it will give SSR node not matching server-rendered errors.

This page will only work if you are logged into backend. DM me for the logins which is here: https://stackhaus-backend.funkhaus.us /wp-admin

Public page: https://pyj86.sse.codesandbox.io/
Private page: https://pyj86.sse.codesandbox.io/featured/private-page

What is expected ?

Cookie header should be sent when both client side and SSR

What is actually happening?

SSR gives node not matching server-rendered errors

Additional comments?

I'm running WordPress as a headless CMS and trying to get preview/draft/private pages/posts working. The setup results in the backend having a different domain to your frontend, like example.com and api.example.com.

modogo2000

modogo2000 posted a new question

apollo-module •

GraphQL error: Missing authorization header.

Hello,

I'm new with with apollo module. I have some difficulties to use apollo module.

I have to send a header Authorization: Bearer secret.

I try this :

apollo: {
authenticationType: 'Bearer',
clientConfigs: {
default: {
httpEndpoint: 'https://graphql.fauna.com/graphql',
getAuth: () => 'Bearer xxxxx'
}
}

but i have this error error message : GraphQL error: Missing authorization header.

How can I header the http header.

Best regards

yaki4

yaki4 posted a new feature request

apollo-module •

idea Disable default watcher loading if one is specified in query

What problem does this feature solve?

If i use a watcher loading in my apollo config, this watcher is called every time i made a query.
It's great if i want to work the same way every time, but if i've got one query where i want to manage the loading anothre way it doesn't work.

apollo: {
watchLoading: '~/plugins/apollo-watch-loading-handler.js',
clientConfigs: {
default: '~/apollo/client-configs/default.js'
},
includeNodeModules: true
},

query example :
dataSpecific: {
query: require('@/apollo/queries/dataSpecificQuery'),
variables () {
return {
ids: XXXX
}
},
update (data) {
return data
},
watchLoading (isLoading) {
console.log("i'm the only one who works')
}
}

yaki4

yaki4 posted a new question

apollo-module •

Disable default watcher loading if one is specified in query.

If i use a watcher loading in my apollo config, this watcher is called every time i made a query.
It's great if i want to work the same way every time, but if i've got one query where i want to manage the loading anothre way it doesn't work.

apollo: {
watchLoading: '~/plugins/apollo-watch-loading-handler.js',
clientConfigs: {
default: '~/apollo/client-configs/default.js'
},
includeNodeModules: true
},

query example :

dataSpecific: {
query: require('@/apollo/queries/dataSpecificQuery'),
variables () {
return {
ids: XXXX
}
},
update (data) {
return data
},
watchLoading (isLoading) {
console.log("i'm the only one who works')
}
} 
leviwheatcroft

leviwheatcroft posted a new bug report

apollo-module •

bug custom link doesn't work when declared in apollo.config.js

Version

v4.0.0-rc.19

Reproduction link

https://codesandbox.io/s/romantic-volhard-oz2dd?fontsize=14&hidenavigation=1&theme=dark

Steps to reproduce

Run repro. See error.

What is expected ?

link to be loaded as apollo link

What is actually happening?

type error: x.concat is not a function

Additional comments?

After much consternation, I've tracked this down to this part of templates/plugin.js.

Essentially, if you provide a clientConfig as an object within nuxt.config.js, then it will be JSON.stringified. ApolloLink.prototype.toString() returns {}, so after stringification & parsing you get a plain empty object. Later when this is passed to ApolloLink.from, it will try to the link's concat method which doesn't exist because it's just a plain object.

In your nuxt.config.js if you define clientConfigs as a reference to another file like:

  clientConfigs: {
    default: '~/plugins/apollo/apollo.default.js'
  }

it will work as expected, because the config doesn't get stringified.

ctmqwe

ctmqwe posted a new question

apollo-module •

Apollo addSmartQuery in Vuex?

Query gql function with parameters in Vue-Apollo via
this.$apollo.addSmartQuery
in Nuxt apollo-module in components as in docs of Vue-Apollo, but in vuex this.app.apolloProvider.defaultClient (missing addSmartQuery function)

How to work in Nuxt Vuex with Apollo queries functions?

websitevirtuoso

websitevirtuoso posted a new feature request

apollo-module •

idea Apollo onLogin token expiration in seconds

What problem does this feature solve?

By documentation we have
this.$apolloHelpers.onLogin(token /* if not default you can pass in client as second argument, you can set custom cookies attributes object as the third argument, and you can skip reset store as the fourth argument */)

We can set up ttl in days. But my App using ttl in seconds (2-5 hours for example)

Right now I extend my middleware like this one

export default function ({ app, error }) {
  const tokenExpireDateTime = app.$cookies.get(AUTH_TOKEN_EXPIRE)
  const tokenTtl = app.$moment(tokenExpireDateTime).diff(app.$moment(), 'seconds')
  const hasToken = !!app.$apolloHelpers.getToken()
  if (!hasToken || tokenTtl < 0) {
    error({ statusCode: 403, message: 'Permission denied', description: 'Sorry, you are forbidden from accessing this page.' })
  }

It solves a problem but anyway the best way use ttl in seconds

ozum

ozum posted a new question

apollo-module •

Query which depends on result of another query (SSR)

I have two queries X and Y. A variable of Y is taken from result of 'X'. I want to execute both queries on server side. How to achieve that?

Below simplified example is closest I can get, but query Y is executed at client side.

{
  apollo: {
    X: {
      query: X
    },
    Y: {
      query: Y,
      variables() {
        return { id: this.X.someField };
      },
      skip() {
        return !this.X;
      }
    },
  }
}

Basically I want:

  1. Execute query X on server and get result.
  2. Execute query Y on server with a variable from result of query X.

Many thanks,

ozum

ozum posted a new bug report

apollo-module •

bug Cannot provide `inMemoryCacheOptions.cacheRedirects`

Version

v4.0.0-rc.19

Reproduction link

https://jsfiddle.net/35twv906/

Steps to reproduce

Add cacheRedirects to inMemoryCache as seen in https://jsfiddle.net/35twv906/

See: https://www.apollographql.com/docs/react/performance/performance/

What is expected ?

Having Apollo Cache Redirects.

What is actually happening?

No cache redirect is happening.

Also .nuxt/apollo-module.js has below code. See cacheRedirects.Query is empty.

defaultClientConfig = {
  "httpEndpoint": "http://localhost:8080/v1/graphql",
  "inMemoryCacheOptions": {
    "cacheRedirects": {
      "Query": {}
    }
  }
suenot

suenot posted a new question

apollo-module •

loading is not defined

In plugins/apollo-watch-loading-handler.js

export default (isLoading, countModifier, nuxtContext) => {
  loading += countModifier
  console.log('Global loading', loading, countModifier)
}

My nuxt.config:

// import colors from 'vuetify/es5/util/colors'

export default {
  mode: 'universal',
  /*
  ** Headers of the page
  */
  head: {
    titleTemplate: '%s - ' + process.env.npm_package_name,
    title: process.env.npm_package_name || '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: process.env.npm_package_description || '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  /*
  ** Customize the progress-bar color
  */
  loading: { color: '#fff' },
  /*
  ** Global CSS
  */
  css: [
  ],
  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
    { src : '~/plugins/vue-apexchart.js', ssr : false },
    { src : '~/plugins/v-charts.js', ssr : false },
  ],
  /*
  ** Nuxt.js dev-modules
  */
  buildModules: [
    '@nuxtjs/vuetify',
  ],
  /*
  ** Nuxt.js modules
  */
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/auth',
    '@nuxtjs/apollo'
  ],
  /*
  ** vuetify module configuration
  ** https://github.com/nuxt-community/vuetify-module
  */
  vuetify: {
    customVariables: ['~/assets/variables.scss'],
    theme: {
      dark: true,
      themes: {
        // dark: {
        //   primary: colors.blue.darken2,
        //   accent: colors.grey.darken3,
        //   secondary: colors.amber.darken3,
        //   info: colors.teal.lighten1,
        //   warning: colors.amber.base,
        //   error: colors.deepOrange.accent4,
        //   success: colors.green.accent3
        // }
      }
    }
  },
  /*
  ** Build configuration
  */

  build: {
    // vendor : ['vue-apexchart'],
    /*
    ** You can extend webpack config here
    */
    extend (config, ctx) {
    }
  },
  serverMiddleware: ['./auth'],
  axios: {
    proxy: true
  },
  proxy: {
    '/api': 'http://localhost:3000'
  },
  auth: {
    redirect: {
      callback: '/callback'
    },
    strategies: {
      auth0: {
        domain: 'suenot.eu.auth0.com',
        client_id: 'NkwwJnyxYqp5uTifYg_LCqBiQ6SWWMyo'
      },
    }
  },
  apollo: {
    tokenName: 'apollo-token', // optional, default: apollo-token
    cookieAttributes: {
      /**
        * Define when the cookie will be removed. Value can be a Number
        * which will be interpreted as days from time of creation or a
        * Date instance. If omitted, the cookie becomes a session cookie.
        */
      expires: 7, // optional, default: 7 (days)

      /**
        * Define the path where the cookie is available. Defaults to '/'
        */
      path: '/', // optional
      /**
        * Define the domain where the cookie is available. Defaults to
        * the domain of the page where the cookie was created.
        */
      domain: 'http://localhost:3000/', // optional

      /**
        * A Boolean indicating if the cookie transmission requires a
        * secure protocol (https). Defaults to false.
        */
      secure: false,
    },
    includeNodeModules: true, // optional, default: false (this includes graphql-tag for node_modules folder)
    authenticationType: 'Basic', // 'Basic', // optional, default: 'Bearer'
    // (Optional) Default 'apollo' definition
    defaultOptions: {
      // See 'apollo' definition
      // For example: default query options
      $query: {
        loadingKey: 'loading',
        fetchPolicy: 'cache-and-network',
      },
    },
    // optional
    watchLoading: '~/plugins/apollo-watch-loading-handler.js',
    // optional
    errorHandler: '~/plugins/apollo-error-handler.js',
    // required
    clientConfigs: {
      default: {
        // required
        httpEndpoint: 'https://suenot-hasura.herokuapp.com/v1/graphql',
        // optional
        // override HTTP endpoint in browser only
        browserHttpEndpoint: '/graphql',
        // optional
        // See https://www.apollographql.com/docs/link/links/http.html#options
        httpLinkOptions: {
          credentials: 'same-origin'
        },
        // You can use `wss` for secure connection (recommended in production)
        // Use `null` to disable subscriptions
        // wsEndpoint: 'wss://suenot-hasura.herokuapp.com/v1/graphql', // optional
        // LocalStorage token
        // tokenName: 'auth._token.auth0', // optional
        // Enable Automatic Query persisting with Apollo Engine
        persisting: false, // Optional
        // Use websockets for everything (no HTTP)
        // You need to pass a `wsEndpoint` for this to work
        websocketsOnly: false // Optional
      },
      // test: {
      //   httpEndpoint: 'http://localhost:5000',
      //   wsEndpoint: 'ws://localhost:5000',
      //   tokenName: 'apollo-token'
      // },
      // alternative: user path to config which returns exact same config options
      // test2: '~/plugins/my-alternative-apollo-config.js'
    }
  }
}
kapilgohil

kapilgohil posted a new question

apollo-module •

Apollo or Axios

Hi All,

So I am currently using Apollo to query an external graphql endpoint (Shopify storefront API)

Should I be using Apollo or Axios?
What are the differences?

Thanks