Git Product home page Git Product logo

apollo's Issues

window.__NUXT__.apollo is undefined

Getting this error attempting to use this module on an app built with nuxt generate. No initial state is available.

With this line:

        initialState: window.__NUXT__.apollo.<%= key === 'default' ? 'defaultClient' : key %>,

What happens when no initial state is available? How would I tell my client that I don't have an initial state payload for it?

This question is available on Nuxt.js community (#c8)

Nuxt generate support for dyamic routes?

Hi there, this might be a bit project-specific, but is it possible to get nuxt.js working with this apollo module in terms of dynamic routes generation?

Example (small part of my app – the main question is at the end, but the intro may be useful to read, too, thanks in advance):

I have an app, listing some shops that I get from an API (obviously...) and I list them in pages/shops/index.vue via the following:

index.vue content: (apollo part only):

apollo: {
    allShops: {
      prefetch: true,
      query: allShops,
      update (data) {
        return data.site.shops.by_category.edges        

      },
      variables () {
        return {
          language: this.$store.state.language,
          category: this.category
        }
      },
      skip () {
        return !this.$store.state.language
      }
    }
  }

allShops.gql content:

  site(language: $language) {    
    shops { 
      by_category(category: $category, pagination: {sort: {field: name}, limit: 100}) {
        total
        edges {
          node {
            id
            slug
            name 
            latitude
            longitude
            opening_html
          }
        }
      }
    }
  }
}

This list works perfectly, I can filter, search, etc etc, but this is not the main point :)

shops/_slug.vue content for a single shop (the apollo part only):

apollo: {
    Shop: {
      query: shop,
      update (data) {
        return data.site.shops.by_slug
      },
      prefetch: ({ route }) => ({ slug: route.params.slug }),
      variables() {
        return { slug: this.$route.params.slug }
      }
    }
  }

shop.gql content for a single shop, by slug:

query Shop($slug: String!) {
  site {
    shops {
      by_slug(slug: $slug) {
        id
        slug
        name
        latitude
        longitude            
      }
    }
  }
}

These stuff work like a charm, the app is fast, with smooth transitions and fast load times, (thumbs up, @Atinux, @alexchopin and @Akryum – and of course, the whole team).

BUT HOW DO I GENERATE ALL THES SHOPS' DYNAMIC ROUTES WITH NUXT.JS?
I actually have no idea (this is my fault, I am still learning GraphQL... So if anyone has any idea how to generate all the shops' routes like /shops/shop-slug.html, please help :)

All comments are appreaciated, and maybe this is just an issue because of my lack of knowledge on promises, payload or whatever this requires :)

Thnak you!

This question is available on Nuxt.js community (#c50)

TypeError: Cannot read property 'Ctor' of undefined

After update to v2.0 and Nuxt .rc7 I receive the following error on page reload on server side:

[vue-server-renderer] error when rendering async component:
TypeError: Cannot read property 'Ctor' of undefined

the page still loads and seems to work.

This question is available on Nuxt.js community (#c16)

Authorization

In the times I've used vanilla Apollo, I pass an Authorization header via the network interface opts. This is how the API authorizes graphql access. I can do that using Nuxt, but I've only gotten as far as hardcoding the token into nuxt.config.js in my initial R&D. For instance:

modules: ['@nuxtjs/apollo'],
apollo: {
    clients: {
        default: {
            uri: 'https://example.com/graphql',
            opts: { 
                headers: { 
                    Authorization: 'Bearer ABCDEF1234567'
                }
            }
        }
    }
}

So I guess my question is two-fold:

  1. Server-side, how can I dynamically set the network interface options? For instance, setting the Bearer token from a cookie sent in the request. In a previous version of Nuxt, I was able to do that using a custom auth middleware (cookie.parse(req.headers['cookie']).

  2. Once the app hits the browser, if the user's token is stored in local storage, how would I update the network interface with the new options?

EDIT: See below for current working solution to this
TL;DR use Nuxt middleware to access Apollo middleware. Steps:

  1. Extract the token from an HTTP Only cookie. You can either:
    1. bake the token extraction logic into an app-specific Apollo middleware
    2. extract in nuxtServerInit
  2. Assign the token to the store. This makes the token accessible in the browser. Also necessary if you went the nuxtServerInit route, as you need a way to get the token into the next step
  3. Create a Nuxt middleware that applies an Authorization header via apollo's applyMiddleware method. This is possible because the apollo clients are accessible via context.app.apolloProvider (examples below)
  4. Run the middleware on any page/layout that apollo auth is needed.
This question is available on Nuxt.js community (#c2)

Unable to find native implementation, or alternative implementation for WebSocket!

I got this error when follow the guide on readme.

Unable to find native implementation, or alternative implementation for WebSocket!

default.js

import { ApolloLink, concat, split } from 'apollo-link'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { WebSocketLink } from 'apollo-link-ws'
import { getMainDefinition } from 'apollo-utilities'
import 'subscriptions-transport-ws' // this is the default of apollo-link-ws

export default (ctx) => {
  const httpLink = new HttpLink({uri: 'https://api.graph.cool/simple/v1/' + process.env.GRAPHQL_ALIAS})
  const authMiddleware = new ApolloLink((operation, forward) => {
    const token = process.server ? ctx.req.session : window.__NUXT__.state.session
    operation.setContext({
      headers: {
        Authorization: token ? `Bearer ${token}` : null
      }
    })
    return forward(operation)
  })
  // Set up subscription
  const wsLink = new WebSocketLink({
    uri: `wss://subscriptions.graph.cool/v1/${process.env.GRAPHQL_ALIAS}`,
    options: {
      reconnect: true,
      connectionParams: () => {
        const token = process.server ? ctx.req.session : window.__NUXT__.state.session
        return {
          Authorization: token ? `Bearer ${token}` : null
        }
      }
    }
  })
  
  const link = split(
    ({query}) => {
      const {kind, operation} = getMainDefinition(query)
      return kind === 'OperationDefinition' && operation === 'subscription'
    },
    wsLink,
    httpLink
  )

  return {
    link: concat(authMiddleware, link),
    cache: new InMemoryCache()
  }
}
This question is available on Nuxt.js community (#c46)

Server Side rendering : "You must wrap the query string in a "gql" tag"

Hello ! Apollo is amazing with Vue.js et Nuxt.js, thanks so much @Akryum and @Atinux !
But i have a stranger error on SSR : this throw a 500 error on production server : https://yineo-website-xzfiffgbwg.now.sh/

You must wrap the query string in a "gql" tag.

BUT if work if you go first to contact page, and let client rendered the homepage : https://yineo-website-xzfiffgbwg.now.sh/contact

here is my apollo call :

<template>
  <Presentation :posts="postsQuery.results" />
</template>

<script>
import Presentation from '~/components/Presentation'
import postsQuery from '~/apollo/queries/postsQueryHomepage'
export default {
  transition: 'page',
  components: { Presentation },
  apollo: {
    postsQuery: {
      query: postsQuery,
      prefetch: true
    }
  }
}
</script>

for whatever reason, if i build it locally (npm run build && npm run start), this error does not appear :-/

This question is available on Nuxt.js community (#c11)

Module build failed: Duplicate declaration "client"

nuxt.config.js

  apollo: {
    clientConfigs: {
      default: '~/apollo/client-configs/client1.js',
      client2: '~/apollo/client-configs/client2.js'
    }
  },

Error:

 ERROR  Failed to compile with 1 errors                                 10:35:11

 error  in ./.nuxt/apollo.plugin.0bafa84e.js

Module build failed: Duplicate declaration "client"

  41 | 
  42 |   
> 43 |     let client = require('~/apollo/client-configs/client2.js')
     |         ^
  44 |     // es6 module default export or not
  45 |     client = client.default(ctx) || client(ctx)
  46 |     const cache = client.cache || new InMemoryCache()


 @ ./.nuxt/index.js 286:0-98
 @ ./.nuxt/client.js
 @ multi webpack-hot-middleware/client?name=client&reload=true&timeout=30000&path=/__webpack_hmr ./.nuxt/client.js

bildschirmfoto von 2017-12-22 10-36-41

https://github.com/nuxt-community/apollo-module/blob/master/plugin.js#L18

This question is available on Nuxt.js community (#c40)

compatibility with nuxt Generate?

Is apollo-module compatible with generate? When I run generate, I get the following with Error: ENOENT: no such file or directory, lstat '/Users/Alex/Sites/temp/nuxtlotest/dist/index.html.

yarn generate
yarn run v1.3.2
$ nuxt generate
  nuxt:generate Generating... +0ms
  nuxt:build App root: /Users/Alex/Sites/temp/nuxtlotest +0ms
  nuxt:build Generating /Users/Alex/Sites/temp/nuxtlotest/.nuxt files... +1ms
  nuxt:build Generating files... +14ms
  nuxt:build Generating routes... +5ms
  nuxt:build Building files... +31ms
Build completed in 12.368s

Hash: 8e589c9f082a2d25ae41
Version: webpack 3.8.1
Time: 12374ms
                                  Asset       Size  Chunks             Chunk Names
    pages/index.ba3b400b8c2db044bc9d.js    3.93 kB       0  [emitted]  pages/index
layouts/default.bb1fbffadd7a97ccccdd.js     1.4 kB       1  [emitted]  layouts/default
         common.82aed720f1f0ae6edbcd.js     274 kB       2  [emitted]  common
            app.91b26017724725808d3d.js    26.9 kB       3  [emitted]  app
       manifest.8e589c9f082a2d25ae41.js    1.59 kB       4  [emitted]  manifest
                               LICENSES  634 bytes          [emitted]  
 + 8 hidden assets
Hash: ba275b1a3579d8eb0730
Version: webpack 3.8.1
Time: 1284ms
             Asset    Size  Chunks             Chunk Names
server-bundle.json  326 kB          [emitted]  
  nuxt:generate Destination folder cleaned +0ms
  nuxt:generate Static & build files copied +34ms
Generating routes
  nuxt:render Rendering url / +0ms
{ Error: ENOENT: no such file or directory, lstat '/Users/Alex/Sites/temp/nuxtlotest/dist/index.html'
  errno: -2,
  code: 'ENOENT',
  syscall: 'lstat',
  path: '/Users/Alex/Sites/temp/nuxtlotest/dist/index.html' }
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
This question is available on Nuxt.js community (#c26)

These dependencies were not found

I have error when try apollo-module. Here is my full error

ERROR  Failed to compile with 5 errors                                                                                       14:34:28
These dependencies were not found:

* apollo-link-http in ./apollo/client-configs/default.js
* graphql/language/printer in ./node_modules/apollo-cache-inmemory/lib/writeToStore.js, ./node_modules/apollo-client/index.js and 2 others

To install them, you can run: npm install --save apollo-link-http graphql/language/printer

Any idea?

By the way, I'm using Windows 10 - Node 8.9.1

This question is available on Nuxt.js community (#c33)

I don't understand apollo-module SSR behavior

Hello there !

When you go here AND then click on "blog" page (the first time ) https://yineo-website-kqpewkcldg.now.sh/blog/contact
What i get :

  1. Loading bar at the top go to 100% loaded, but posts are not yet loaded
  2. My blogs posts are displaying "loading"
  3. Blog posts appears once pulled by apollo from my GraphQL API server

What i expected :

  • Blog posts already rendered as html string by nodejs server (edit : that is the normal behavior because when you came from "contact" page, blog page is then loaded by client side when we click on it, my bad)~~
  • OR : loading bar do not go up until 100% if posts are not yet loaded

Am i doing something wrong here ?
Are posts actually Server Side rendered ? (edit : yes they are if you visit url directly : https://yineo-website-kqpewkcldg.now.sh/blog)

See the corresponding code here :
https://github.com/nyl-auster/yineo-front/blob/fc0a4882f6565757552dff94352089db3b0e59ff/pages/blog/index.vue

This question is available on Nuxt.js community (#c20)

start() finished() loading animation sync with apollo query result

It would be great if this module could hook the apollo query to the start(), finished() function of the global loading component.

 apollo:{
   query:`someQuery`,
   watchLoading(isLoading){
      // => it would be great if the isLoading variable could be synchronized with the nuxt state change behaviour
          // following is not working:
          if (isLoading) {
            this.$root.$loading.start()
          } else {
            this.$root.$loading.finish()
          }
   } 
 }
}
This feature request is available on Nuxt.js community (#c17)

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Once you have installed CI on this repository, you’ll need to re-trigger Greenkeeper’s initial Pull Request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper integration’s white list on Github. You'll find this list on your repo or organiszation’s settings page, under Installed GitHub Apps.

This question is available on Nuxt.js community (#c7)

Cannot read property 'session' of undefined on production

Not really sure where to post this, so if there's an existing issue that would be great! Trying to debug this currently. I've basically put my Nuxt/Apollo project onto Now. It works, except it throws me this error:

client.js:37 [nuxt] Error while initializing app TypeError: Cannot read property 'session' of undefined

which is referring to this line:

// auth token
  let token = ctx.isServer ? ctx.req.session : window.__NUXT__.state.session

For some reason on a production server it cannot find 'session' - any help here would be appreciated! :) (Merry Christmas!)

This question is available on Nuxt.js community (#c42)

Question about set auth token

Hi, maybe it is a dummie question, but I need your help :(

I'm looking for best practicing about set rauth token to use with nuxt. How to do it right?

Here is my login method

methods: {
    emailLogin () {
      console.log(this)
      const { email, password } = this.$data
      this.$apollo.mutate({
        mutation: UserLogin,
        variables: {
          email,
          password
        }
      }).then((result) => {
        Cookies.set('authToken', result.data.authenticateUser.token)
        this.$store.commit('SET_AUTH_TOKEN', result.data.authenticateUser.token)
      }).catch((error) => {
        console.log(error)
      })
    }
}

My store

export const state = () => ({
  authToken: null,
  authUser: null
})

export const mutations = {
  SET_AUTH_TOKEN: function (state, token) {
    state.authToken = token
  }
}

export const actions = {
  nuxtServerInit ({ commit }, { req }) {
    if (req.session && req.session.authToken) {
      commit('SET_AUTH_TOKEN', req.session.authToken)
    }
  }
}

and my Apollo config

import { ApolloLink } from 'apollo-link'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'

export default (ctx) => {
  const httpLink = new HttpLink({ uri: 'https://api.graph.cool/simple/v1/cjaeub9io2kcz0115e4m0ql6d' })

  // auth token
  let token = ctx.isServer ? ctx.req.authToken: window.__NUXT__.state.authToken

  // middleware
  const middlewareLink = new ApolloLink((operation, forward) => {
    operation.setContext({
      headers: { authorization: `Bearer ${token}` }
    })
    return forward(operation)
  })
  const link = middlewareLink.concat(httpLink)
  return {
    link,
    cache: new InMemoryCache()
  }
}
This question is available on Nuxt.js community (#c34)

No client appened to this.$apollo

I reproduced the error in this repo: https://github.com/jarnojellesma/graphql-experiment/tree/master/client

nuxt.config:

module.exports = {
  modules: ['@nuxtjs/apollo'],
  apollo: {
    clientConfigs: {
      default: '~/apollo/client-configs/default.js'
    }
  },
  rootDir: path.resolve(__dirname),
  srcDir: path.resolve(__dirname),
};

apollo/client-configs/default:

export default (ctx) => {
  const httpLink = new HttpLink({ uri: 'http://localhost:3030/graphql' })
  console.log('default client');

  console.log(ctx.isServer)

  const middlewareLink = new ApolloLink((operation, forward) => {
    return forward(operation)
  })
  const link = middlewareLink.concat(httpLink)
  return {
    link,
    cache: new InMemoryCache()
  }
};

Now the client is supposed to be accessible on the this.$apollo within component methods. But it is undefined:

imageedit_2_9091224975

This question is available on Nuxt.js community (#c41)

Custom network interface / subscription strategy with nuxt

I'm in the process of porting an old React project to Vue, and noticed nuxt. My custom network-interface is a websocket interface that supports subscriptions. When the websocket is terminated, the network-interface re-sends subscriptions to the server.

With the apollo-module is it (in-)appropriate to set up a websocket connection to the server where components can subscribeToMore?

Should I somehow limit my components to not create subscriptions if they're running on the server? And then, would I somehow scan my application when in a browser to create these subscriptions?

This question is available on Nuxt.js community (#c27)

How to implement middleware on networkInterface?

What is the correct way to implement middleware on the networkInterface?

Normaly I would to something like this

import { createNetworkInterface } from 'apollo-client';

const networkInterface = createNetworkInterface({
  uri: 'https://api.graph.cool/simple/v1/cj4zq9w43ru8u0175d1zniy6q',
  transportBatching: true,
});

networkInterface.use([{
  applyMiddleware(req, next) {
    if (!req.options.headers) {
      req.options.headers = {};  // Create the header object if needed.
    }
    const token = ssr ? getTokenFromCookie() : getTokenFromLocalStorage()

    req.options.headers.authorization = token ? `Bearer ${token}` : null;
    next();
  }
}]);

Not sure how this would work in apollo-module

This question is available on Nuxt.js community (#c5)

How to create a BatchingNetworkInterface?

The current implementation uses the createNetworkInterface to create a normal NetworkInterface (which is fine in most cases).

But if we want to use query batching, we have to create a BatchingNetworkInterface (using createBatchingNetworkInterface as in this example.

How can we do that with this module?

This question is available on Nuxt.js community (#c1)

"Network error: fetch is not defined" running example from Nuxt repository

Changed into the examples/vue-apollo directory, ran:

npm install
npm dev

Visited http://localhost:3000, and received this error.

I don't know if this is the best/correct solution, but when I set up Apollo without this plugin, I had to add the isomorphic-fetch package and run:

import "isomorphic-fetch"

to define a fetch global. I'm not sure if doing this globally is the right way, but as of now the example isn't working, so if using isomorphic-fetch isn't correct then there should probably be modifications made to get the example working.

Thanks.

This question is available on Nuxt.js community (#c6)

Nuxt 1.1.0 problem

I update nuxt to 1.1.0 version. And errors showing up :(

C:\Users\xxxxxx\Desktop\web>npm run dev

> [email protected] dev C:\Users\xxxxxx\Desktop\web
> nuxt

  nuxt:axios BaseURL: http://localhost:3000/api (Browser: /api) +0ms

 ERROR  Nuxt error

  Error: Invalid vendor:vue-apollo,apollo-client,apollo-cache-inmemory

  - module.js:28 ModuleContainer.addVendor
    [web]/[nuxt]/lib/core/module.js:28:13

  - index.js:27 ModuleContainer.nuxtApollo
    [web]/[@nuxtjs]/apollo/index.js:27:8

  - module.js:150 Promise
    [web]/[nuxt]/lib/core/module.js:150:30

  - new Promise

  - module.js:134 ModuleContainer.addModule
    [web]/[nuxt]/lib/core/module.js:134:12

  - utils.js:96 promise.then
    [web]/[nuxt]/lib/common/utils.js:96:43


  - next_tick.js:188 process._tickCallback
    internal/process/next_tick.js:188:7

  - module.js:678 Function.Module.runMain
    module.js:678:11

  - bootstrap_node.js:187 startup
    bootstrap_node.js:187:16

  - bootstrap_node.js:608
    bootstrap_node.js:608:3


  nuxt:build App root: C:\Users\xxxxxx\Desktop\web +0ms
  nuxt:build Generating C:\Users\xxxxxx\Desktop\web\.nuxt files... +0ms
  nuxt:build Generating files... +64ms
  nuxt:build Generating routes... +12ms
  nuxt:build Building files... +43ms
  nuxt:build Adding webpack middleware... +146ms
  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ 100%

Build completed in 6.15s



 ERROR  Failed to compile with 6 errors                                                                                       11:12:30
These dependencies were not found:

* ~/apollo/queries/PostList in ./node_modules/babel-loader/lib?{"babelrc":false,"cacheDirectory":true,"presets":[["C://Users//xxxxxx//Desktop//web//node_modules//babel-preset-vue-app//dist//index.common.js",{"targets":{"ie":9,"uglify":true}}]]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./pages/index.vue
* ~/apollo/queries/PostSearch in ./node_modules/babel-loader/lib?{"babelrc":false,"cacheDirectory":true,"presets":[["C://Users//xxxxxx//Desktop//web//node_modules//babel-preset-vue-app//dist//index.common.js",{"targets":{"ie":9,"uglify":true}}]]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./components/Navbar.vue
* ~/apollo/queries/PostSingle in ./node_modules/babel-loader/lib?{"babelrc":false,"cacheDirectory":true,"presets":[["C://Users//xxxxxx//Desktop//web//node_modules//babel-preset-vue-app//dist//index.common.js",{"targets":{"ie":9,"uglify":true}}]]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./pages/xem/_slug/index.vue, ./node_modules/babel-loader/lib?{"babelrc":false,"cacheDirectory":true,"presets":[["C://Users//xxxxxx//Desktop//web//node_modules//babel-preset-vue-app//dist//index.common.js",{"targets":{"ie":9,"uglify":true}}]]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./pages/xem/_slug/_ep.vue
* ~/apollo/queries/UserByID in ./node_modules/babel-loader/lib?{"babelrc":false,"cacheDirectory":true,"presets":[["C://Users//xxxxxx//Desktop//web//node_modules//babel-preset-vue-app//dist//index.common.js",{"targets":{"ie":9,"uglify":true}}]]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./components/Navbar/UserMenu.vue
* ~/apollo/queries/UserLogin in ./node_modules/babel-loader/lib?{"babelrc":false,"cacheDirectory":true,"presets":[["C://Users//xxxxxx//Desktop//web//node_modules//babel-preset-vue-app//dist//index.common.js",{"targets":{"ie":9,"uglify":true}}]]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./components/Navbar/LoginForm.vue

To install them, you can run: npm install --save ~/apollo/queries/PostList ~/apollo/queries/PostSearch ~/apollo/queries/PostSingle
~/apollo/queries/UserByID ~/apollo/queries/UserLogin

 OPEN  http://localhost:3000
This question is available on Nuxt.js community (#c47)

add store or other SSR context to "prefetch"

Hello,

It would be great if prefetch will get the SSR context of Nuxt, for example the store. I have for example the language of a document saved as store.state.languageKeyand would like to prefetch this state variable. Would this be somehow possible?
Thanks

This question is available on Nuxt.js community (#c14)

Response headers and request session are never accessible at the same time

When I receive a response through apollo, I can access response.headers.get('refreshToken') to get my server token.

But it seems to be accessible on client-side only, I have to add

if (process.browser) {
    response.headers.get('accessToken')
}

req.session however, seems to be accessible only on server-side.
Is it not possible to store tokens received on response.headers inside req.session?

This question is available on Nuxt.js community (#c32)

Apollo Queries null after updating to Nuxt 1.0

I'm currently using apollo-module 3.0.1.

After upgrading to Nuxt 1.0, apollo queries do not work when navigating to new pages and I get an error about queries being null. If I refresh and pull from the server however, the data does come through as expected. This is happening across multiple projects and only fails after using Nuxt 1.0.

Has anyone else run into this issue?

This question is available on Nuxt.js community (#c45)

SSR for Graphql Queries

Hi, I'm new to Nuxt. Below is the code that fetches customer after rendering everything from the client. Can I make it SSR so that the query will be loaded right from the server?

Here is the code that I'm using:

<template>
  <pre>{{customer}}</pre>
</template>

<script>
import CUSTOMER from '~/apollo/customer.gql';

export default {
  apollo: {
    customer: {
      query: CUSTOMER
    }
  }
}
</script>
This question is available on Nuxt.js community (#c37)

Fix context deprecations

  1. context.isServer is deprecated
context.isServer has been deprecated, please use process.server instead.
  1. context.isClient is deprecated
context.isClient has been deprecated, please use process.client instead.
This question is available on Nuxt.js community (#c43)

Get store in network-interfaces/default.js

I have the following network-interfaces/default.js file

import { createNetworkInterface } from 'apollo-client'
import { SubscriptionClient, addGraphQLSubscriptions } from 'subscriptions-transport-ws'

const ssr = process.server

// Create the network interface
const networkInterface = createNetworkInterface({
  uri: '',
  transportBatching: true,
});

networkInterface.use([{
  applyMiddleware(req, next) {
    if (!req.options.headers) {
      req.options.headers = {};  // Create the header object if needed.
    }
    
    const token = // need the store here. 


    req.options.headers.authorization = token ? `Bearer ${token}` : null;
    next();
  }
}]);

let networkInterfaceWithSubscriptions;

// Create the subscription websocket client
if (! ssr) {
  const wsClient = new SubscriptionClient('', {
    reconnect: true,
    timeout: 20000
  });

  // Extend the network interface with the subscription client
  networkInterfaceWithSubscriptions = addGraphQLSubscriptions(
    networkInterface,
    wsClient,
  );
}

const networkInterfaceObj = ssr ? networkInterface : networkInterfaceWithSubscriptions

export default networkInterfaceObj

How can I call the vuex store context here? So I can set the Bearer token from the vuex store

I use the nuxtServerInit function to set the token to the store

   nuxtServerInit({ commit }, { req }) {
      if (req.session && req.session.token) {
         commit('SET_TOKEN', req.session.token)
      }
    }
This question is available on Nuxt.js community (#c12)

Apollo Client 2.0.4 incompatibility or lack of documentation

My attempt is to use apolloProvider errorHandler method just like in these docs.
However I keep getting the error

In order to initialize Apollo Client, you must specify link & cache properties on the config object. This is part of the required upgrade when migrating from Apollo Client 1.0 to Apollo Client 2.0.

Here is my apollo/client-configs/default.js

import { ApolloLink } from 'apollo-link'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import VueCookies from 'vue-cookies'
import { ApolloClient } from 'apollo-client'
import VueApollo from 'vue-apollo'

export default (ctx) => {
  const httpLink = new HttpLink({ uri: 'http://localhost:3001/graphql' })

  // middleware
  const middlewareLink = new ApolloLink((operation, forward) => {
    operation.setContext({
      headers: {
        accessToken: VueCookies.get('accessToken') || '',
        refreshToken: VueCookies.get('refreshToken') || ''
      }
    })
    return forward(operation)
  })
  const link = middlewareLink.concat(httpLink)

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

  const apolloProvider = new VueApollo({
    defaultClient: apolloClient,
    errorHandler (error) {
      console.log('Global error handler')
      console.error(error)
    }
  })

  return {
    apolloProvider
  }
}
This question is available on Nuxt.js community (#c38)

Reactive queries prefetch cannot depend on component data

I'm not sure if this is an issue with this module or vue-apollo.

Apparently the prefetch is called twice on server side rendering, first before initiating the component, and then after the component is initialised.

When using a reactive variables function for the query parameters, the function is called twice during server rendering, the first time is before the component is initialised, with the nuxt context as this (no component data available), and then a second time with the component instance as this.

This makes it impossible for any queries that rely on component data for it's parameters to be prefetched on server rendering. That I can see, the only way to use reactive parameters and prefetch is by using the vuex store.

Maybe I'm doing something wrong..

Here is an example that will now work:

data () {
  return {
    placeId: 123
  }
},
apollo: {
  places: {
    prefetch: true,
    query: gql`query index($id: Int!, $range:Int!) {
      places: placesNear(id: $id, range: $range) {
        distance
        place {
          id
          name
          location
          address
        }
      }
    }`,
    variables () {
      return {
        id: this.placeId, // this will not work on ssr
        range: 10000 
      }
    }
  }
}

This will work:

variables () {
  const state = this.$store ? this.$store.state : this.store.state
  return {
    id: state.placeId, // ok
    range: 10000 
  }
}
This question is available on Nuxt.js community (#c49)

Duplicate Result of apollo query

I integrated the apollo-module and every thing is working great but I am facing a weird problem. After I get result, I customize it to meet my need which is working just fine but Each time a gql query is executed, it returns the result two times which is causing the end result to appear twice.
2018-01-03_2144
as you can see that first time posts object is recieved, it updates the allPosts object but then it again gets updated to twenty and hence the duplicated result. my code is this:

export default {
data() {
    return {
	allPosts:[],
	charLength: 40
	}
},
apollo: {
	posts: {
	  prefetch: true,
	  query: allPosts,
	  result ({data: {posts}}) {
	    console.log('posts ', posts.length)
	    posts.forEach(post => {
	     this.allPosts.push(Object.assign({},post,{
	        body: `${post.body.substr(0, this.charLength)}...`
		}))
          });
          console.log('all-posts ', this.allPosts.length)
				}
			},
		},
		head() {
			return {title: "All posts"}
		}
	};

is it related to vue-apollo or nuxt? or something else?

note: If I don't customize the result, everything works normal.

This question is available on Nuxt.js community (#c44)

Seeking debugging advice

Hitting a very strange issue and am seeking advice on how to debug this. I'm creating a network interface like so:

import {createNetworkInterface} from "apollo-phoenix-websocket"

let host = process.browser ? location.origin.replace(/^http/, "ws") : "ws://127.0.0.1:4000"
if(process.browser)
  host = host.replace("3000", "4000")

export default () => createNetworkInterface({
  uri: `${host}/socket`
})

This function definitely gets called and returns an interface, but my requests are sent over HTTP to a /graphql endpoint on 3000 rather than to the Phoenix websocket at /socket on port 4000. Further, when I do:

  mounted() {
    console.log("Mounted", this.$apollo.provider.clients.defaultClient.networkInterface)
  },

in a component, I see a network interface with /graphql as the URI. Something somewhere seems to be creating a default network interface, guessing that my GraphQL endpoint is at localhost:3000/graphql rather than at localhost:4000/socket where my interface explicitly points, but I can't find what that might be.

My thought was to check out the raw module source into node_modules and start adding console.logs, but I see lines like:

    <% if (key === 'default') { %>

I don't immediately see how to run code with these templating lines in it. Is there some preprocessing step I have to run to add debugging code into the module?

Failing that, is there some known place in the code where a network interface with a /graphql URI might be created? My backend has its endpoint at either localhost:4000/api or localhost:4000/socket, so nowhere am I creating this.

To be clear, I don't think the issue is in this module, but this module is where I'd start to debug the problem, and while I see these template lines throughout the Nuxt code, nowhere do I see an explanation of what they are.

Thanks.

This question is available on Nuxt.js community (#c24)

Store cache issue

Hello,

I have an issue, when I have routes with nuxt child, I've a cache fail on parent routes. You can see the issue here : https://github.com/Nainterceptor/nuxt.js/tree/issue/store-cache/examples/vue-apollo (or live in https://nuxt-vue-apollo-elszaxsupq.now.sh).

I'm on the homepage, I click on a car, I refresh, then I click on another car, the main list disappear.

I'm trying to find the issue without sucess (And of course it's working when I disable cache)

Thanks for your help !

This question is available on Nuxt.js community (#c15)

Validate GraphQL response before render

Hello, thanks for module!

I have a question: is there a way to validate apollo response before render?

I have a page /pages/users/_username.vue and I want to render proper Not Found page along with 404 status code if username is not found (when graphql returns null).

Currently I have to something like this:

<template>
  <div>
    <div v-if="user">
      <h1>{{user.fullName}}</h1>
    </div>
    <div v-else >
      User is not found :(
    </div>
  </div>
</template>

It'd be great to handle graphql response in the same way nuxt's validate hook works.

This question is available on Nuxt.js community (#c28)

store.state is false on client refresh in v2.0 networkInterface default function

@Atinux thanks for merging my PR but it seems to not work properly:

defaultNetworkInterface.js
export default ({store, req, isServer} ) => {
  let token
  if (isServer) {
    token = getTokenFromCookie(req)
    token && store.commit('SET_AUTH_TOKEN', token)
  } else {
    token = store.state.authToken
  }
  console.log(isServer, token) // => token is always empty on client side
}

The network interface is missing the store states on isServer===false.

This brings me to a general question: how is Vuex supposed to work? If users commit a Vuex store state on server side, should the Vuex state be present on client side as well? I think the plugin/module behaviour might miss to persist the correct Vuex state at the moment

This question is available on Nuxt.js community (#c13)

best practice to use apollo inside of Vuex

@Akryum @Atinux do you guys have an idea what would be the best practice to attach $apollo or apolloProvider to Vuex and make it accessible inside of actions? Would be great to be able doing:

this.$store.dispatch('mutateGql',variables) 

// inside of store.js
mutateGql({apollo?},context){
// => how to get current apollo instance inside of the action?
}

Any thought how to do this with this module?

This feature request is available on Nuxt.js community (#c21)

queries in nested pages are not reactive

When both a parent container and a child contain a query, the reactive query for the child is not updated.

Example:

- _profile.vue
  - _post.vue // nested child, queries speficic post (this is not updated on route change)
  - index.vue
- _profile.vue // profile container, queries all user posts (this query is updated)

But if I change the page setup so that the queries aren't nested, it works:

- _profile.vue
  - _post.vue // queries speficic note (this query updates now)
  - index.vue // queries all user notes (but not container anymore)
- _profile.vue // no queries here now

I think this is due to the fact that the data method, which vue-apollo uses, it not called again, only asyncData method is called again when reactive data changes. But I'm not sure why nesting the pages influences this.

I've tried moving the apollo query outside of the pages, but this did not change anything. Not being able to nested pages/queries is severely limiting. I will try using vanilla apollo with asyncData to see if this changes anything, but opening this issue so you're aware of the problem.

This question is available on Nuxt.js community (#c48)

Error: 'Schema must be an instance of GraphQLSchema' - When connect with ApolloServer

i try to use with apollo server and do as the tutorials.
http://dev.apollodata.com/tools/apollo-server/index.html

it work fine until add apollo-module, the error happend.

my Project https://github.com/lyquocnam/simple

Error: Schema must be an instance of GraphQLSchema. Also ensure that there are not multiple versions of GraphQL installed in your node_modules directory.
This question is available on Nuxt.js community (#c18)

Can't load .gql files after upgrading.

When following the steps on the readme to upgrade to version 3.0, none of the of my .gql queries load. It instead asks me to install them manually.

I've updated the official Nuxt example and put it in a repository that can be found here to show the issue. If anyone could help me fix my configuration that would be greatly appreciated. I've been waiting a few weeks for someone else to have the same problem, but so far it looks like its only me. Thanks!

This question is available on Nuxt.js community (#c36)

Unable to use Nuxt's error/redirect functionality when a query failed

I want to call the context.error({...}) to show the Nuxt's error page when a query failed (Item not found, etc.).

In asyncData(context) {...}, we can easily do that as context is always given.

However inside vue-apollo's smart queries, I can't find a way to access the error()

This feature request is available on Nuxt.js community (#c30)

$apollo undefined in context.app

If i try to use apollo in fetch or asyncData, $apollo is not defined in context.app:

async fetch ({ app, store }) {
  const { data } = await app.$apollo.query({
    query: gql`query { posts: { id } }`
  })
}

For now I use this work around but I'm just curious why $apollo isn't defined.

async fetch ({ app, store }) {
  const { data } = await app.apolloProvider.defaultClient.query({
    query: gql`query { posts: { id } }`
  })
}
This question is available on Nuxt.js community (#c10)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.