Activities

randyhoulahan

randyhoulahan posted a new bug report

apollo-module •

bug gql files not resolving by babel - only in circleci

Version

v4.0.0-rc.14

Reproduction link

https://circleci.com/gh/circusliving/amp/32

Steps to reproduce

the files resolve fine everywhere except in circleci's node circleci/node:latest.
I have tried with and without extension gql

What is expected ?

the files to resolve

What is actually happening?

Module not found: Error: Can't resolve '../apollo/webPageByPath.gql' in 'modules'

Additional comments?

I have "graphql-tag": "^2.10.1", in my deps

colinmeinke

colinmeinke posted a new feature request

apollo-module •

idea Local state documentation

What problem does this feature solve?

Give an example of how to create and use a client to store local state in a Nuxt app. I spent a bunch of time trying to work this out without success, and found the documentation unhelpful.

What does the proposed changes look like?

Additions to the readme.

HaNdTriX

HaNdTriX posted a new question

apollo-module •

Cookies are not removed on the server

Description

@nuxtjs/apollo uses universal-cookie this module can read cookies but afaik it doen't modify the res. So it can't remove the cookie.

res.setHeader('Set-Cookie', ['token=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT']);

This means onLogout and onLogin have issues when they are beeing called on the server.

Code

rchl

rchl posted a new feature request

apollo-module •

idea Don't require default client to be defined

What problem does this feature solve?

It makes it possible to use the module without having default client defined.

This should be possible now that vue-apollo removed need for it in https://github.com/Akryum/vue-apollo/issues/548

What does the proposed changes look like?

Remove this check:
https://github.com/nuxt-community/apollo-module/blob/c9756814c49e0dae7ed4ce450af740bb791dd824/lib/module.js#L16

tdwells90

tdwells90 posted a new question

apollo-module •

Async getToken for authorization header

Hi,

I'm using AWS Cognito with amplify for authenticating my users and they offer a set of asynchronous functions for getting the access token, id token etc. I want to set the authorization header of my app using the access token provided, but it seems I can't use the getAuth override if it's an async function?

Here's my apollo config file so you can see what I'm trying to achieve:

import { Auth } from 'aws-amplify'

const getToken = async () => {
  try {
    const session = await Auth.currentSession()
    const retrieveToken = session.getAccessToken()
    return retrieveToken.getJwtToken()
  } catch (e) {
    return ''
  }
}

export default () => {
  const endpoint = 'blah blah'

  return {
    httpEndpoint: endpoint,
    getAuth: async () => await getToken()
  }
}

So, how can I set the Authorization header with the getToken() function? Is there a way using the apollo module or do I need to use vue-apollo (or even vanilla apollo) to get this working?

Any help would be greatly appreciated!

Thanks,

Tom.

lewebsimple

lewebsimple posted a new feature request

apollo-module •

idea Implement file upload support

What problem does this feature solve?

Right now, file uploads using the GraphQL multipart request specification are not possible with nuxt-apollo.

Adding support for apollo-upload-client shouldn't be too hard to implement.

What does the proposed changes look like?

If I understand correctly, the upload link simply replaces the HTTP link inside the client config.
From the end-user's perspective, this tutorial should give an idea of how things work on the frontend.

slavanossar

slavanossar posted a new feature request

apollo-module •

idea Evaluate client config at runtime

What problem does this feature solve?

Currently, the httpEndpoint in the clientConfigs is baked into the apollo-module.js template at build time. This causes issues in deployment pipelines that rely on immutable builds and promoting compiled code from staging to production (e.g. Heroku), i.e.

• App is first built in staging environment, with httpEndpoint defined by staging env var being hardcoded into resulting .nuxt/apollo-module.js.
• Compiled code is promoted from staging to production.
• Production environment is now using staging httpEndpoint.

See this issue for a more in-depth explanation.

What does the proposed changes look like?

No API/config changes would be required, just that the apollo-module.js template would be updated to instead evaluate the apollo options in nuxt.config.js at runtime.

slavanossar

slavanossar posted a new question

apollo-module •

HTTP Endpoint environment variable hardcoded into app bundle

While trying to deploy a Nuxt app to Heroku, I came across the problem where the Apollo HTTP endpoint is hardcoded into the generated apollo-module.js on build within the staging environment. This means that when the compiled app bundle is promoted from staging to production, the module doesn't use the production HTTP endpoint specified in the production environment variables.

Not sure if this is a module specific issue, or one related to Nuxt as a whole.

nuxt.config.js

apollo: {
  clientConfigs: {
    default: {
      httpEndpoint: process.env.APOLLO_HTTP_ENDPOINT
    }
  }
}
educob

educob posted a new question

apollo-module •

$apolloHelpers.onLogin(token, '/', { expires: 7 }) creating a cookie with different path.

Hello.

I use $apolloHelpers.onLogin when logging in but also in method mounted in the default layout, to recover the user record when the browser is refreshed.

If after logging in the user goes to, let's say, to path /wallets and refreshes the page a 2nd cookie with path /wallets is created and user management doesn't work.

How can I force $apolloHelpers.onLogin to create a cookie only in path '/'?

Thanks.

code to recover user data when refreshing browers:

  async mounted() {
    const token = this.$apolloHelpers.getToken()
    if(!!token) {
      const user = await this.$apollo.query( { // how to call a query when needed.
        query: gql`query user($token: String) {
          user(token: $token) {
            _id
            nick
            defaultAddress
            opts {
              _id
              name
              userId
              value
            }
          }
        }`,
        variables: {
          token: token,
        },
      }).then(({data}) => data && data.user)
      console.log("user:", user)
      if(user) {
        await this.$apolloHelpers.onLogin(token, '/', { expires: 7 })
        this.$store.commit("user/set", user)
      }
    }
  },

Apollo configuration in nuxt.conf.js:

 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. */
      /** * 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', // optional, default: 'Bearer'
    // (Optional) Default 'apollo' definition
    defaultOptions: {
      // See 'apollo' definition for example: default query options
      $query: {
        loadingKey: 'loading',
        fetchPolicy: 'cache-and-network',
      },
    },
    // optional
    errorHandler: '~/plugins/apollo-error-handler.js',
    // required
    clientConfigs: {
      default: {
        // required  
        httpEndpoint: 'http://localhost:4000/graphql',
        // optional. See https://www.apollographql.com/docs/link/links/http.html#options
        httpLinkOptions: {
          credentials: 'same-origin',
          headers: {
            'user-agent': 'Server agent'
          }
        },
        // You can use `wss` for secure connection (recommended in production)
        // Use `null` to disable subscriptions
        wsEndpoint: 'ws://localhost:4000/graphql', // optional
        // LocalStorage token
        tokenName: 'apollo-token', // 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:4000/graphql',
        wsEndpoint: 'ws://localhost:4000/graphql',
        tokenName: 'apollo-token'
      },
    }
  },
IngvarListard

IngvarListard posted a new question

apollo-module •

Restore cache after SSR

How to restore cache after SSR? Vue-apollo docs says:

  if (!ssr) {
    if (typeof window !== 'undefined') {
      const state = window.__APOLLO_STATE__
      if (state) {
        // If you have multiple clients, use `state.<client_id>`
        cache.restore(state.defaultClient)
      }
    }
  }

But on client side there is no any of __APOLLO_STATE__ variable on window. The only thing what I found is __NUXT__ variable, which has a field state which is object, but I can't use restore method with this state.

ScreamZ

ScreamZ posted a new bug report

apollo-module •

bug Typescript issue VueApolloOptions

Version

v4.0.0-rc.12

Reproduction link

https://no.fr

Steps to reproduce

Try to compile with nuxt-build, see the error with tsc /node_modules/vue-apollo/types/options"' has no exported member 'VueApolloOptions'.

What is expected ?

This should be correctly typed or ignored…

What is actually happening?

This is not

dohomi

dohomi posted a new question

apollo-module •

websockets authentication fails due to the use of vue-cli-plugin-apollo

Hi

I just found out in a different project that vue-cli-plugin-apollo does not work with authentication:
https://github.com/Akryum/vue-cli-plugin-apollo/pull/144

So currently I wonder if anybody uses websockets at all? Because ultimately all the authorization should fail

Maybe this plugin should wire up its own config being independent or should reference the PR patch

pandastein

pandastein posted a new question

apollo-module •

Uncaught Error: Cannot use e "__Schema" from another module or realm.

Hi I'm using @nuxt/apollo-module in my NuxtJS project. Everything works fine… But ! Because there is always a but… (and sorry for my english).

On local environment I have this error :

Uncaught Error: Cannot use e "__Schema" from another module or realm.

I googled and no one solution works for me. I tried to post my issue on discord or other community platform but no answer to solve this issue.
The error break all my javascript, so it hold me on this…

Here my repo to see my code if needed : https://bitbucket.org/Pandastein/dws-client/src/master/

And a screenshot to show the complete error I have in my console window.

I hope someone can help me and unlock me for I continue to build my project, please.

Regards,

Capture d’écran, le 2019-09-09 à 19.14.53.png

Jones-S

Jones-S posted a new question

apollo-module •

I get JSON response but Error: "Network error: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data"

I am using apollo and fetch data from within my vuex store asynchronously.

I finally resolved all CORS and authorization issues and the network tab says I am getting the correct response:

Screenshot 2019-09-09 at 15.47.09.png

But still I would get an error saying:

"Network error: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data"

I have absolutely no idea what to do, as I think the response is here and correct.

Screenshot 2019-09-09 at 15.49.22.png

can I somewhere define the return type for apollo and this might be misconfigured?
Or how else could I start debugging?

I have also to mention that my apollo client normally works if used like this:

export default {
  apollo: {
    foo: {
      query: fooGql,
      variables () {
        return {
          myVar: this.myVar
        }
      }
    }
  }
}

But when using the apollo client within my store:

export const actions = {
  loadData({ state, dispatch, commit, getters }, payload) {
    logV(m, 'loadData() action start')

    dispatch('loadGlobalSettings')
    dispatch('loadNavigations', { sections: config.sections })
  },
  async loadNavigations({ state, commit }, payload) {
    logV(m, 'loadNavigations() action start')
    commit('NAVI_LOAD')

    const navigations = {}

    try {
      const apolloClient = this.app.apolloProvider.defaultClient

      const { sections } = payload

      // get all entries for each section
      for (const section of sections) {
        const pages = await apolloClient
          .query({
            query: gql`
              ${navigationsQuery}
            `,
            variables: { section }
          })
          .then(result => {
            console.log('📩 result: ', result)
            // return data.entries
          })
          .catch(error => {
            console.log('errorito: ', error)
          })
        navigations[section] = pages
      }

      commit('NAVIGATIONS_SAVE', navigations)
      commit('NAVI_LOAD_DONE')
    } catch (e) {
      logV(m, 'loadNavigations() action failed 😢: ', e)
    }
    logV(m, '📦 Navigations saved 📦')
    logV(m, 'loadNavigations() action done')
  },

I get this error above…

Here is my apollo client config:

import {
  IntrospectionFragmentMatcher,
  InMemoryCache
} from 'apollo-cache-inmemory'
import introspectionQueryResultData from '../fragmentTypes.json'
import config from '~/config.js'


export default function({ isDev, env }) {
  const fragmentMatcher = new IntrospectionFragmentMatcher({
    introspectionQueryResultData
  })
  const token = config.env.GRAPHQL_TOKEN
  const endpoint = `${config.env.BACKENDURLPRODUCTION}${config.env.GRAPHQL_PATH}`

  const cache = new InMemoryCache({ fragmentMatcher })

  return {
    httpEndpoint: endpoint,
    httpLinkOptions: {
      credentials: 'include',
      fetchOptions: {
        mode: 'no-cors'
      }
    },
    getAuth: () => `Bearer ${token}`,
    cache
  }
}

If anyone with more experience with apollo could help me out here, I would be incredibly thankful!
Cheers

--- PS:
What I also don't understand:
I have an apollo error handler defined iny my nuxt.config

/*
   ** Apollo config
   */
  apollo: {
    includeNodeModules: true,
    errorHandler: '~/apollo/plugins/apolloErrorHandler.js',
    clientConfigs: {
      default: '~/apollo/client-configs/default.js'
    }
  },

But this would never log anything. Does this error handler not handle errors when apolloclient is used like I do it from the store?

Jones-S

Jones-S posted a new question

apollo-module •

CORS problem when fetching data from within store

Hi everyone.

I am using the nuxt apollo module once within my pages, just like this:

apollo: {
    entries: {
      query: page,
      prefetch: ({ route }) => ({
        slug: removeLeadingSlash(route.params.slug)
      }),
      variables() {
        let slug = this.$route.params.slug
        slug = removeLeadingSlash(slug)
        return { slug }
      }
    }
    },

This works fine and I am getting the data.

I also load some global data async from my store.

export const actions = {
  async loadData({ state, dispatch, commit, getters }, payload) {
  // ....
  const pages = await apolloClient
          .query({
            query: gql`
              ${navigationsQuery}
            `,
            variables: { section }
          })
          .then(({ data }) => {
            console.log('data: ', data)
            return data.entries
          })
          .catch(error => {
            console.log('error: ', error)
          })
  // ...
  }
}

But this does not work in my client because of CORS.

I tried a few things with my apollo client config:

import {
  IntrospectionFragmentMatcher,
  InMemoryCache
} from 'apollo-cache-inmemory'
import introspectionQueryResultData from '../fragmentTypes.json'
import config from '~/config.js'

export default function({ isDev, env }) {
  const fragmentMatcher = new IntrospectionFragmentMatcher({
    introspectionQueryResultData
  })

  const endpoint = `${config.env.BACKENDURLPRODUCTION}${config.env.GRAPHQL_PATH}`

  const cache = new InMemoryCache({ fragmentMatcher })

  return {
    httpEndpoint: endpoint,
    httpLinkOptions: {
      fetchOptions: {
        mode: 'no-cors' // Cors Needed for external Cross origins, need to allow headers from server
      }
    },
    getAuth: () => `Bearer ${token}`,
    cache
  }
}

With

      fetchOptions: {
        mode: 'no-cors'
      }

or:

      fetchOptions: {
        mode: 'cors' // Cors Needed for external Cross origins, need to allow headers from server
      }

I am not getting the CORS error anymore but now I am getting this:

Error: "Network error: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data"

Anyway I read that one should use proxies:
https://github.com/nuxt-community/apollo-module#proxies

But how should I set up a proxy?
And why should that solve my CORS problem?

I tried adding the proxy module, but that would not help right (in my case it did not)?

modules: [
    '@nuxtjs/proxy',
    '@nuxtjs/axios',
    '@apollo
]

also as far as I understand I can use the proxy module to go to another url instead.

So If I was using an apollo client trying to fetch data from /graphql it would automatically go to https://mycms.com/graphql. But in my case my apollo client config already points to the absolute url and it also works in the case where I use apollo within my page components.

Also I have to mention that if I use this neat little plugin (https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/) for firefox to bypass all CORS issues it indeed works.

What am I missing and what could I do to remove my CORS stuff?

PS: I am positive that I have set the right .htaccess to allow all domains on the server (craft cms).
Also I think that if that was not the case I could not fetch any graphql stuff at all – but as I said it works for the page-related data.

<IfModule mod_rewrite.c>
    Header set Access-Control-Allow-Origin "*"
    Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
    Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

    RewriteEngine on

    # Redirect root to /web, which is the initial entry point, but don't show it in the URL
    RewriteRule ^/?$ /web/
</IfModule>

I would very much appreciate some help here, because I just can't get it to work, and I am absolutely clueless, what else I could do.

thank you a thousand times in advance.

cheers

LuXDAmore

LuXDAmore posted a new bug report

apollo-module •

bug Using Apollo-module in middleware cause HTML to grow up

Version

v4.0.0-rc.12

Reproduction link

nuxt-apollo-middleware

Steps to reproduce

Install apollo-module for Nuxt;
Use a query from 'apollo' in a middle-ware.

What is expected ?

The HTML doesn't not have to grow up on every navigation.

What is actually happening?

The HTML grow up since ~ 100 MB.

Additional comments?

Using apollo.cache.data.clear(); before the apollo.query() remove the issue.
I've tried to remove the cache in the default-config, but without success.

(In my project i need in-cache-memory because i have some Fragments, but unfortunately i don't have a valid example for that.)

zachheine

zachheine posted a new question

apollo-module •

Setting up apollo-cache-persist with nuxt

I'm trying to follow the setup instructions at https://github.com/apollographql/apollo-cache-persist/blob/master/README.md#web but I cannot figure out where the await persistCache() function should go. I'm guessing in a plugin but I cannot figure out how to do this. Here is some of my config: https://stackoverflow.com/questions/57780294/client-apollo-gql-tag-breaks-query.

firstaml-dima

firstaml-dima posted a new question

apollo-module •

Why is Apollo unable to do onLogin from NuxtServerInit?

Hi all,

I've got an async NuxtServerInit() function, which contains:

const currentToken = await app.$apolloHelpers.getToken()
console.log('current Apollo token = ', currentToken)

if (!currentToken) {
    await app.$apolloHelpers.onLogin(cookies.auth.token)

    const updatedToken = await app.$apolloHelpers.getToken()
    console.log('updated Apollo token  = ', updatedToken)
}

updatedToken is always null. Could you please help me identify the problem?

Thanks!

cjustinobi

cjustinobi posted a new question

apollo-module •

How do I mock ApolloMutation component?
import { createLocalVue, shallowMount } from '@vue/test-utils'
import VueApollo from '@nuxtjs/apollo'
import Register from '../pages/register/index.vue'

describe('Register user', () => {

  let localVue
  beforeEach(() => {
    localVue = createLocalVue()
    localVue.use(VueApollo, {})
  })

  it('Should click the register button to register', () => {

    const mutate = jest.fn()
    const wrapper = shallowMount(Register, {
      localVue,
      mocks: {
        $apollo: {
          mutate,
        }
      }
    });

    wrapper.find('.callMe').trigger('click')
    expect(2+2).toBe(4)
  });
});

It is throwing error TypeError: Cannot read property 'build' of undefined

Please what is the proper way to do this?

orblazer

orblazer posted a new question

apollo-module •

Add Setup details for Typescript config.

Hello,
I thinks its a good idea to write an note for typescript setup, this could avoid an useless issues.

For setup we need add @nuxtjs/apollo, vue-cli-plugin-apollo and vue-apollo in tsconfig.json (compilerOptions.types).

Thanks