Activities

lewebsimple

lewebsimple posted a new feature request

apollo-module •

idea Example usage with Vue Composition API

What problem does this feature solve?

Vue-Apollo 4.x.x alpha release is based on the new Vue Composition API. Would be great to be able to use it with @nuxtjs/apollo

MarcelloTheArcane

MarcelloTheArcane posted a new question

apollo-module •

Bug: Expired JWT throws an unhandled error

I am using Hasura for the GraphQL server, and when a JWT is invalid (in this case expired), it returns the following error:

image

This causes an unhandled error which breaks my app. In development, I see this nuxt error:

image

And this is logged to the console:

image

In Zeit, which I am using for production, I get an Unknown application error occurred error which completely breaks the app.

image

Zeit logs show:

image

Ncaffeine

Ncaffeine posted a new question

apollo-module •

support `graphql-config` config manage graphql configs

graphql-config is awesome plugin for graphql.graphql-config

i want not need manager multiple graphql url in project.
Ex:
1.in nuxt.config.ts file
apollo: { defaultOptions: { $query: { loadingKey: 'loading', fetchPolicy: 'cache-and-network' } }, clientConfigs: { default: { httpEndpoint: 'https://my-url' } } }

  1. in .graphqlconfig config file
    { "name": "xxx", "schemaPath": "./schema.graphql", "extensions": { "endpoints": { "Default GraphQL Endpoint": { "url": "https://my-url" } } } }
jsbroks

jsbroks posted a new bug report

apollo-module •

bug Cache not transferred from server to client on SSR

Version

v4.0.0-rc.18

Reproduction link

codesandbox

Steps to reproduce

In the code sandbox:

  1. Open the console tab
  2. Refresh the page (to make sure the page is rendered SSR)
  3. Read the output from the console

In a project:

  1. Load any apollo data on server-side
  2. Read the apollo on client-side

What is expected ?

The output of the cache on mounted to match the output of the cache on asyncData when rendered SSR

What is actually happening?

The output of the cache on mounted is empty.

Additional comments?

This behavior can also be observed with any SSR render (including nuxtServerInit)

kimjisung78

kimjisung78 posted a new question

apollo-module •

Why can't use $apollo, $apolloHelpers?

My Version
@nuxtjs/apollo : 4.0.0-rc18
nuxt : 2.10.2

My tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "esnext",
"moduleResolution": "node",
"lib": [
"esnext",
"esnext.asynciterable",
"dom"
],
"esModuleInterop": true,
"experimentalDecorators": true,
"sourceMap": true,
"strict": true,
"allowSyntheticDefaultImports": true,
"noEmit": true,
"noImplicitAny": false,
"baseUrl": ".",
"resolveJsonModule": true,
"paths": {
"~/": ["./"]
},
"types": [
"@nuxt/types",
"@nuxtjs/axios",
"@nuxtjs/apollo",
"vue-cli-plugin-apollo"
]
}
}

My used .vue
import Vue from 'vue'

enum Operators {
ADD,
SUBTRACT,
MULTIPLE,
DEVIDE
}
interface Data {
Operators: typeof Operators;
left: string | null;
right: string | null;
operator: Operators;
}

export default Vue.extend({
data (): Data {
return {
Operators,
left: null,
right: null,
operator: Operators.ADD
}
},
computed: {
answer (): number {
if (!this.left || !this.right) { return 0 }
const left = Number(this.left)
const right = Number(this.right)
switch (this.operator) {
case Operators.ADD:
return left + right
case Operators.SUBTRACT:
return left - right
case Operators.MULTIPLE:
return left * right
case Operators.DEVIDE:
return left / right
default:
return 0
}
}
}
})

Why can't use $apollo, $apolloHelpers?

renestalder

renestalder posted a new bug report

apollo-module •

bug Smart Query in SSR "Cannot set property X of #<Object> which has only a getter" when query name isn't identical as variable setting in update method

Version

v4.0.0-rc.18

Reproduction link

https://codesandbox.io/s/nuxt-apollo-ssr-production-t4ytk

Steps to reproduce

Difficult to provide exact steps for reproducing the issue, as it only happens with universal mode (ssr) and when the smart query name doesn't match what the update function writes to a variable

  1. Create a smart query with a query called "myQuery1"
  2. Add an update function and save the data provided in the update function to a variable e.g. myData.
  3. Run application server-side

See the codesandbox for a code example. Sadly, you would have to run the code locally. For reproducing it, it needs to run in production mode and with 'universal' mode (ssr enabled).

What is expected ?

No issues

What is actually happening?

Cannot set property myQuery1 of #<Object> which has only a getter

Additional comments?

The issue can be fixed by having a data property with the exact name of the query. This then is super confusing in a way.

Here's an example code from a production application I'm running.

This works:

apollo: {
    category(): CategoryProductsQueryDefinition {
      return {
        query: CategoryProducts,
        fetchPolicy: 'cache-and-network',
        update(data) {
          if (data.paginatedProducts && data.category) {
            this.paginatedProducts = data.paginatedProducts;
            this.category = data.category;
          }
        },
        result({data, loading, networkStatus}) {
          this.isLoading = false;
        },
        variables() {
          const categoryId = this.$route.params.id;
          const isUser = this.$store.getters[userGettersMap[UserGetterType.LoggedIn]];
          const filterQueryVariables = this[FilterGetterType.ActiveProductFiltersAPIParams];

          return {
            ...filterQueryVariables,
            // That's for the paginatedProductsQuery
            categoryIds: categoryId ? [categoryId] : null,
            // That's for the category detail query
            categoryId,
            isUser
          };
        },
        skip() {
          const isUser = this.$store.getters[userGettersMap[UserGetterType.LoggedIn]];
          return !this.$route.params.id || (process.server && isUser);
        }
      };
    }
  },

This does not (mind the query name of getCategoryPageData).

apollo: {
    getCategoryPageData(): CategoryProductsQueryDefinition {
      return {
        query: CategoryProducts,
        fetchPolicy: 'cache-and-network',
        update(data) {
          if (data.paginatedProducts && data.category) {
            this.paginatedProducts = data.paginatedProducts;
            this.category = data.category;
          }
        },
        result({data, loading, networkStatus}) {
          this.isLoading = false;
        },
        variables() {
          const categoryId = this.$route.params.id;
          const isUser = this.$store.getters[userGettersMap[UserGetterType.LoggedIn]];
          const filterQueryVariables = this[FilterGetterType.ActiveProductFiltersAPIParams];

          return {
            ...filterQueryVariables,
            // That's for the paginatedProductsQuery
            categoryIds: categoryId ? [categoryId] : null,
            // That's for the category detail query
            categoryId,
            isUser
          };
        },
        skip() {
          const isUser = this.$store.getters[userGettersMap[UserGetterType.LoggedIn]];
          return !this.$route.params.id || (process.server && isUser);
        }
      };
    }
  },

Also my Vue components' data doesn't include a property of getCategoryPageData, because why should it? I don't directly use that query result variable, but manually assigning the result.

thebspin

thebspin posted a new question

apollo-module •

Use aws appsync with this module? (cognito userpool and ssr)

Hi, me and my time are converting our product from php/mariadb to vue (nuxt) and graphql.
We want to use this module for our connection to aws appsync as our chosen graphql server.
We found no support on how to to this using this module so we dissect it and used most of your wrapper together with vue-apollo but with no luck.
The calls are being made on the server but they then get returned and a mismatch starts to happen.

Is it not possible at all to use this module with aws-appsync as the graphql server using the userpool auth for that?

Our current client looks like this:

const client = new AWSAppSyncClient(
    {
      url: app.$env.APPSYNC_GRAPHQLENDPOINT,
      region: app.$env.AMPLIFY_REGION,
      disableOffline: true,
      auth: {
        type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS,
        jwtToken: () => store.getters["auth/accessToken"]
      }
    },
    {
      ssrMode: true,
      defaultOptions: {
        watchQuery: {
          fetchPolicy: "cache-and-network"
        }
      }
    }
  )

The wanted behavior is that the initial call is always done server side so that the client does not have to do anything. I hope someone can help and point us in the right direction or even provide the solution!

nice9uy

nice9uy posted a new question

apollo-module •

Nuxt UI

Hi…

Nuxt is very awsome vue framework that very easy to learn.
However, sometimes I have difficulty in setting modules that are quite complicated.
Can nuxt be made like vue ui?

why vue ui? because it is very easy to install modules and without configuration because it is automatic in the installation process, so that new programmers like me can be easy to use and easy to understand how this great nuxt works.

Many thanks a lot

dvjeshka

dvjeshka posted a new feature request

apollo-module •

idea Support for watchLoading function as in vue-apollo package

What problem does this feature solve?

https://apollo.vuejs.org/api/apollo-provider.html#constructor

What does the proposed changes look like?

apollo: {

watchLoading:'~/plugins/apollo-watch-loading.js',
// optional
errorHandler: '~/plugins/apollo-error-handler.js',
// required
clientConfigs: {
default: '~/plugins/apollo-config.js',

    }
},
dvjeshka

dvjeshka posted a new question

apollo-module •

Support for watchLoading function as in vue-apollo package
dvjeshka

dvjeshka posted a new question

apollo-module •

Support for watchLoading function as in vue-apollo package
ashnamuh

ashnamuh posted a new question

apollo-module •

I guess that SSR doesn't work

versions

nuxt: 2.10.0
@nuxtjs/apollo: 4.0.0-rc15

On my Nuxt page component, i wrote following codes

import gql from 'graphql-tag'
import axios from 'axios'
import formatData from '../my/format/func'

export default {
  apollo: {
    forms: {
      query: gql`
        Myquery
      `,
      fetchPolicy: 'cache-first',
      manual: true,
      result({ data, loading }) {
        console.log('log: result')
        if (!loading) {
          console.log('log: result not loading')
          this.myData = formatData(data)
        }
      }
    }
  },
  async asyncData({ app, params, error }) {
    console.log('log: asyncData')
    const { data } = await axios.get('my.api.com/service', { id: params.id })
    if (!data) {
      error({statusCode: 404, message: 'NotFound'})
    }
    return {
      service: data
    }
  },
  data() {
    return {
      myData: null
    }
  },
  created() {
    console.log('log: created')
  },
  mounted() {
    console.log('log: mounted')
  },
}

On the server side log, i expected log: result is printed before log: created like following logs:

log: asyncData
log: result
log: result not loading
log: created

But i got:

log: asyncData
log: created
log: result
log: result not loading

And on the client side browser console, i expected log: result is not printed. But i got:

log: result // i think it is cache log
log: result not loading // i think it is cache log
log: created
log: mounted
log: result
log: result not loading

I don't know what is wrong. I guess apollo smart query is always excuted on the client side. Did i use wrong fetchPolicy?

This question is available on Nuxt community (#c255)
ashnamuh

ashnamuh posted a new question

apollo-module •

I guess that SSR doesn't work

versions

nuxt: 2.10.0
@nuxtjs/apollo: 4.0.0-rc15
On my Nuxt page component, i wrote following codes

import gql from 'graphql-tag'
import axios from 'axios'
import formatData from '../my/format/func'
export default {
 apollo: {
   forms: {
     query: gql`
       Myquery
     `,
     fetchPolicy: 'cache-first',
     manual: true,
     result({ data, loading }) {
       console.log('log: result')
       if (!loading) {
         console.log('log: result not loading')
         this.myData = formatData(data)
       }
     }
   }
 },
 async asyncData({ app, params, error }) {
   console.log('log: asyncData')
   const { data } = await axios.get('my.api.com/service', { id: params.id })
   if (!data) {
     error({statusCode: 404, message: 'NotFound'})
   }
   return {
     service: data
   }
 },
 data() {
   return {
     myData: null
   }
 },
 created() {
   console.log('log: created')
 },
 mounted() {
   console.log('log: mounted')
 },
}

On the server side log, i expected log: result is printed before log: created like following logs:

log: asyncData
log: result
log: result not loading
log: created

But i got:

log: asyncData
log: created
log: result
log: result not loading

And on the client side browser console, i expected log: result is not printed. But i got:

log: result // i think it is cache log
log: result not loading // i think it is cache log
log: created
log: mounted
log: result
log: result not loading

I don't know what is wrong. I guess apollo smart query is always excuted on the client side. Did i use wrong fetchPolicy?

gotenxds

gotenxds posted a new feature request

apollo-module •

idea Support apollo-cache-persist

What problem does this feature solve?

Saving data locally to local storage is imperative for PWA, this is supported by apollo-cache-persist but currently it is unclear/impossible to support it due to the client config not being loaded at the client (mode: client) and thus the window and subsequently the local storage is unavailable.

What does the proposed changes look like?

Ultimately this will be supported internally to support [loading before rendeing] : https://github.com/apollographql/apollo-cache-persist#how-do-i-wait-for-the-cache-to-be-restored-before-rendering-my-app
with an added config option for which store to use.

alternatively allowing to run the apollo config in the client might solve this.

tarunmangukiya

tarunmangukiya posted a new bug report

apollo-module •

bug Seeing extra payload of ssr in apollo that's not requested

Version

v4.0.0-rc.15

Reproduction link

https://iconscout.com

Steps to reproduce

  1. Open chrome console and go into networks tab
  2. Open https://iconscout.com
  3. View and save source code of the page content.
  4. Repeat Step 2 & 3 for 4-5 times
  5. Observe window.__NUXT__ object's apollo variable for all the cases.

You'll see different values for defaultObject.ROOT_QUERY which are not related to this page at all and that's changing on every request. Also, this page is not firing any graphql query at all. And it is adding extra MBs to the response. This response size varies from 1MB to 3.5MB.

You can find response at here https://drive.google.com/open?id=1AS1LUvWkiypbXluy9Pp1TfImyWsApq8L. (I was unable to attach response in here due to its size).

What is expected ?

Usually, each request must have different cache for apollo ssr.

What is actually happening?

I think that in here there might be cached result for some past query and which is being sent to different user in next ssr request.

chriscalo

chriscalo posted a new feature request

apollo-module •

idea Option for separate endpoints for server and client

What problem does this feature solve?

When running locally, the Apollo client on the server and in the browser can both use http://localhost:8000/graphql (or whatever the port is) as the httpEndpoint and everything works fine:

export default {
  modules: [
    "@nuxtjs/apollo",
  ],
  apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: `http://localhost:8000/graphql`,
      },
    },
  },
}

However, when deployed to production (or any other non-local environment), the server can use http://localhost:8000/graphql, but the browser definitely cannot. The simplest solution in my case is for the client value to be just /graphql, and the browser will assume the same domain and port as the currently-running page.

I tried the following workaround in nuxt.config.js of using multiple Apollo clients, but I wasn't able to get it working:

export default {
  modules: [
    "@nuxtjs/apollo",
  ],
  apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: "http://localhost:8000/graphql",
      },
      browser: {
        httpEndpoint: "/graphql",
      },
    },
  },
};

I tried putting the following in every Vue component to dynamically select the right client based on the environment, but got errors in the browser:

<script>
  export default {
    apollo: {
      $client: typeof window === "undefined" ? "default" : "browser",
      // ...
    },
  };
</script>

What does the proposed changes look like?

Both @nuxtjs/axios and @nuxt/http have separate options for the server (baseURL) and the browser (browserBaseURL). It seems the Apollo module needs something similar to support anyone writing an app where their UI and API are running on the same server. (Unless I missed something. Apollo seems to assume that the API is running on a different server.)

export default {
  modules: [
    "@nuxtjs/apollo",
  ],
  apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: "http://localhost:8000/graphql",
        browserHttpEndpoint: "/graphql",
      },
    },
  },
};
wjdrnrdlekt

wjdrnrdlekt posted a new question

apollo-module •

How can i set apollo.clientConfigs in nuxt.config.js for subscription?

I am using GraphQL(Laravel + Lighthouse) + Nuxt.

When i used GraphQL(Laravel + Lighthouse) + vue-apollo , i success subscription.

But after change Nuxt, i dont know idea how can i put config setting.

When i used vue-apollo, my client subscription config is like below.

import { ApolloLink, Observable } from "apollo-link";
import ApolloClient from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'

import Vue from 'vue'
import VueApollo from 'vue-apollo'

class PusherLink extends ApolloLink {
    constructor(options) {
        super();
        // Retain a handle to the Pusher client
        this.pusher = options.pusher;
    }

    request(operation, forward) {
        return new Observable(observer => {
            // Check the result of the operation
            forward(operation).subscribe({
                next: data => {

                    // If the operation has the subscription extension, it's a subscription
                    const subscriptionChannel = this._getChannel(
                        data,
                        operation
                    );
                    console.log(subscriptionChannel);
                    if (subscriptionChannel) {
                        this._createSubscription(subscriptionChannel, observer);
                    } else {
                        // No subscription found in the response, pipe data through
                        observer.next(data);
                        observer.complete();
                    }
                }
            });
        });
    }

    _getChannel(data, operation) {
        return !!data.extensions &&
            !!data.extensions.lighthouse_subscriptions &&
            !!data.extensions.lighthouse_subscriptions.channels
            ? data.extensions.lighthouse_subscriptions.channels[
                  operation.operationName
              ]
            : null;
    }

    _createSubscription(subscriptionChannel, observer) {
        const pusherChannel = this.pusher.subscribe(subscriptionChannel);
        // Subscribe for more update
        pusherChannel.bind('lighthouse-subscription', payload => {
            if (!payload.more) {
                // This is the end, the server says to unsubscribe
                this.pusher.unsubscribe(subscriptionChannel);
                observer.complete();
            }
            const result = payload.result;
            if (result) {
                // Send the new response to listeners
                observer.next(result);
            }
        });
    }
}

const pusherLink = new PusherLink({
    pusher: new Pusher("pusher key", {
        cluster: "ap3",
        authEndpoint: `http://localhost:81/graphql/subscriptions/auth`,
        enabledTransports: ['ws'],
        wsHost: window.location.hostname,
        wsPort: 81,
    })
});

const httpLink = new HttpLink({
    // You should use an absolute URL here
    uri: 'http://localhost:81/graphql',
  })

const link = ApolloLink.from([pusherLink, httpLink]);

// Create the apollo client
const apolloClient = new ApolloClient({
    link,
    cache: new InMemoryCache()
})

Vue.use(VueApollo)

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

const app = new Vue({
    el: '#app',
    apolloProvider
});

I am thinking i should to put my pusherLink to inside of nuxt.config.js

I already learn about plugin of Nuxt and try like below.

nuxt.config.js

.
.
modules: [
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    '@nuxtjs/apollo'
  ],
  /*
  ** Axios module configuration
  ** See https://axios.nuxtjs.org/options
  */
  axios: {
  },

  apollo: {
    clientConfigs: {
      default: '**@/plugins/test.js'** 
    }
  },

plugins/test.js

import { ApolloLink, Observable } from "apollo-link";
import ApolloClient from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'

import fetch from 'node-fetch'
import Pusher from "pusher-js"

import Vue from 'vue'
import VueApollo from 'vue-apollo'

Vue.use(VueApollo)

/*
const app = new Vue({
    el: '#app',
    apolloProvider
}); */


class PusherLink extends ApolloLink {
    constructor(options) {
        super();
        // Retain a handle to the Pusher client
        this.pusher = options.pusher;
    }

    request(operation, forward) {
        return new Observable(observer => {
            // Check the result of the operation
            forward(operation).subscribe({
                next: data => {

                    // If the operation has the subscription extension, it's a subscription
                    const subscriptionChannel = this._getChannel(
                        data,
                        operation
                    );
                    console.log(subscriptionChannel);
                    if (subscriptionChannel) {
                        this._createSubscription(subscriptionChannel, observer);
                    } else {
                        // No subscription found in the response, pipe data through
                        observer.next(data);
                        observer.complete();
                    }
                }
            });
        });
    }

    _getChannel(data, operation) {
        return !!data.extensions &&
            !!data.extensions.lighthouse_subscriptions &&
            !!data.extensions.lighthouse_subscriptions.channels
            ? data.extensions.lighthouse_subscriptions.channels[
                    operation.operationName
                ]
            : null;
    }

    _createSubscription(subscriptionChannel, observer) {
        const pusherChannel = this.pusher.subscribe(subscriptionChannel);
        // Subscribe for more update
        pusherChannel.bind('lighthouse-subscription', payload => {
            if (!payload.more) {
                // This is the end, the server says to unsubscribe
                this.pusher.unsubscribe(subscriptionChannel);
                observer.complete();
            }
            const result = payload.result;
            if (result) {
                // Send the new response to listeners
                observer.next(result);
            }
        });
    }
}

const pusherLink = new PusherLink({
    pusher: new Pusher("pusher-key", {
        cluster: "ap3",
        authEndpoint: `http://localhost:81/graphql/subscriptions/auth`,
        enabledTransports: ['ws'],
        wsHost: "localhost",
        wsPort: 81,
    })
});

const httpLink = new HttpLink({
    // You should use an absolute URL here
    uri: 'http://localhost:81/graphql',
    fetch: fetch,
    })

export default function(context) {
    return {
        httpEndpoint: 'http://localhost:81/graphql',
        wsEndpoint: 'ws://localhost:81/app',
        link: pusherLink,
        cache: new InMemoryCache()
    }
}

But above try was failed. how can i pass my link for nuxt.config.js?

chriscalo

chriscalo posted a new question

apollo-module •

How to set different httpEndpoint for server and browser?

When running locally, the Apollo client on the server and in the browser can both use http://localhost:8000/graphql (or whatever the port is) as the httpEndpoint and everything works fine:

export default {
  apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: `http://${HOST}:${PORT}/graphql`,
      },
    },
  },
}

However, when deployed to production (or any other non-local environment), the server can use http://localhost:8000/graphql, but the browser definitely cannot. For my setup, it's better if the browser doesn't have a host and port at all and instead has only /graphql at the endpoint. Is it possible to do this somehow in nuxt.config.js?

Both @nuxtjs/axios and @nuxt/http have separate options for the server (baseURL) and the browser (browserBaseURL). Seems like the Apollo module should have the same. Does it and I missed it?

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.