nuxt-modules / apollo Goto Github PK
View Code? Open in Web Editor NEWNuxt.js module to use Vue-Apollo. The Apollo integration for GraphQL.
Home Page: https://apollo.nuxtjs.org
License: MIT License
Nuxt.js module to use Vue-Apollo. The Apollo integration for GraphQL.
Home Page: https://apollo.nuxtjs.org
License: MIT License
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?
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!
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.
How can we set the vue-apollo default settings, e.g. the loadingKey
?
See https://github.com/Akryum/vue-apollo#advanced-options
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:
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'])
.
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:
nuxtServerInit
nuxtServerInit
route, as you need a way to get the token into the next stepAuthorization
header via apollo's applyMiddleware
method. This is possible because the apollo clients are accessible via context.app.apolloProvider
(examples below)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()
}
}
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 :-/
Issue #19 was closed but I still get this error.
here is example of my call, I need to use function "update" so metadata defined as a function
import metadataGql from '#/apollo/queries/metadata'
export default {
data () {
return {}
},
apollo: {
metadata () {
return {
query: metadataGql,
update (metadata) {
return metadata
},
}
},
},
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
https://github.com/nuxt-community/apollo-module/blob/master/plugin.js#L18
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 module does not work with 'spa' mode with the latest version of [email protected].
At a glance, it seems there is no window.__NUXT__
since it's not rendered on server side. But I'm not sure how to correctly handle this.
https://github.com/nuxt-community/apollo-module/blob/master/plugin.js#L24
Could anyone fix this?
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
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 :
What i expected :
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
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()
}
}
}
}
π¨ 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.
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!)
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()
}
}
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:
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?
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
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?
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.
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
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.languageKey
and would like to prefetch this state variable. Would this be somehow possible?
Thanks
Is it possible to add custom options to ApolloClient such as queryDeduplication
?
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
?
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?
Not 100% sure, but it appears the "Official Example" linked in the README is out of date:
https://github.com/nuxt/nuxt.js/tree/dev/examples/vue-apollo
Hello, i can't manage to get my page server side rendered with apollo. Here is my code :
https://github.com/nyl-auster/drupal-nuxt-graphql/blob/apollo-ssr-error/pages/blog.vue
and the result : https://komuneco-tkdiaupxhr.now.sh/blog
When using "prefetch:true", i got a fatal error saying "fetch" is not found
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>
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)
}
}
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
}
}
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
}
}
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.
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.
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.
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 !
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.
@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
@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?
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.
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.
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!
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()
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 } }`
})
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.