Activities

xavism

xavism posted a new question

apollo-module •

WS closed when navigating between views

I need an open WS subscription through all the pages that use the same layout (this layout is only accessible if authenticated)
So I added a subscription in the layout's created lifecycle hook. But when I navigate to another view with the same layout, the stop message is automatically sent to the WebSocket to close the connection. Neither created nor destroyed is called so it should work.

What is wrong with this idea? Which is the most elegant way to achieve what I want?
A middleware that runs in all the pages of the layout and creates the connection should work, but it would be creating subscriptions and ending subscriptions all the time :'(

Screenshot 2020-10-29 at 20.41.00.png

ClaudiaGiv

ClaudiaGiv posted a new question

apollo-module •

Does apollo client support transactions?

I have a nuxtjs app that uses apollo module for graphql communication with FaunaDB.
I want to make multiple mutations in one transaction to FaunaDB. So I don't want to send a different request for every single mutation to FaunaDB, I want to make a single request that contains all the mutations. Is it possible?

ferry77

ferry77 posted a new question

apollo-module •

Apollo gql file cannot be resolved by nuxt storybook

The issue similar to this https://github.com/storybookjs/storybook/issues/9581
Do we have solution for nuxt?
Basically I am building nuxt with nuxt apollo and everything running well (no error on 'npm run dev')
After installing nuxt storybook (https://storybook.nuxtjs.org/setup) and run 'npm run storybook'
it comes error like

ERROR in ./pages/menus/index.vue?vue&type=script&lang=js& (./nodemodules/vue-docgen-loader/lib??ref--8!./nodemodules/babel-loader/lib??ref--0-0!./nodemodules/babel-loader/lib??ref--2-0!./nodemodules/@nuxt/components/dist/loader.js??ref--9-0!./node_modules/vue-loader/lib??vue-loader-options!./pages/menus/index.vue?vue&type=script&lang=js&)
Module not found: Error: Can't resolve '~/apollo/queries/fetchMenus' in '/Users/xxxx/nuxt-app/pages/menus'

How can I make Apollo gql to be resolvable by the storybook?

Thank you!

ferry77

ferry77 posted a new question

apollo-module •

Apollo gql file cannot be resolved by nuxt storybook

The issue similar to this https://github.com/storybookjs/storybook/issues/9581
Do we have solution for nuxt?
Basically I am building nuxt with nuxt apollo and everything running well (no error on 'npm run dev')
After installing nuxt storybook (https://storybook.nuxtjs.org/setup) and run 'npm run storybook'
it comes error like

ERROR in ./pages/menus/index.vue?vue&type=script&lang=js& (./nodemodules/vue-docgen-loader/lib??ref--8!./nodemodules/babel-loader/lib??ref--0-0!./nodemodules/babel-loader/lib??ref--2-0!./nodemodules/@nuxt/components/dist/loader.js??ref--9-0!./node_modules/vue-loader/lib??vue-loader-options!./pages/menus/index.vue?vue&type=script&lang=js&)
Module not found: Error: Can't resolve '~/apollo/queries/fetchMenus' in '/Users/xxxx/nuxt-app/pages/menus'

How can I make Apollo gql to be resolvable by the storybook?

Thank you!

SuddenlyRust

SuddenlyRust posted a new bug report

apollo-module •

bug Apollo composables not working

Version

v4.0.1-rc.4
@nuxtjs/[email protected]
@vue/[email protected]

Reproduction link

https://github.com/SuddenlyRust/nuxt-apollo-composables

Steps to reproduce

yarn dev

visit http://localhost:3000/

What is expected ?

Working application without error messages

What is actually happening?

ReferenceError: define is not defined is shown

bug.png

Additional Information

With @vue/[email protected] this error message is not shown.

tecnoloco

tecnoloco posted a new question

apollo-module •

Apollo queries are being fetched on the server and client side (fetched twice)

Setting an apolo query via the apolo Component property will be fetched twice when the page is loaded, on the server (ssr) and the client-side. Is this the expected behavior?

Horlamedhey

Horlamedhey posted a new question

apollo-module •

Dynamic Authorization Issue

My accessToken isn't static as I'm required to login to mongodb realm as a user in order to access the data, I use anonymous signing which means that the token will always change. I've tried all possible methods that I know of and also follow all solutions in all threads dating back to 2018 but I still can't get it working. I get this error
Network error: Response not successful: Received status code 401
Please help.

lielfr

lielfr posted a new bug report

apollo-module •

bug normalQuery test not passing

Version

v4.0.1-rc.1

Reproduction link

https://codesandbox.io/s/nervous-murdock-jjtmq?file=/src/index.js

Steps to reproduce

  1. Use the provided server as the endpoint.
  2. Install the packages.
  3. Run the test script.

What is expected ?

The tests should pass.

What is actually happening?

The normalQuery test fails.

``` ● basic › normalQuery

expect(received).toContain(expected) // indexOf

Expected substring: "cjw1jhoxi1f4g0112ayaq3pyz"
Received string:    "<!doctype html>
<html data-n-head-ssr>
  <head >
    <title>Normal Query</title><style data-vue-ssr-id=\"3191d5ad:0\">.nuxt-progress{position:fixed;top:0;left:0;right:0;height:2px;width:0;opacity:1;-webkit-transition:width .1s,opacity .4s;transition:width .1s,opacity .4s;background-color:<a href="https://github.com/undefined/undefined/issues/000" target="_blank">#000</a>;z-index:999999}.nuxt-progress.nuxt-progress-notransition{-webkit-transition:none;transition:none}.nuxt-progress-failed{background-color:red}</style>
  </head>
  <body >
    <div data-server-rendered=\"true\" id=\"__nuxt\"><!----><div id=\"__layout\"><div><ul><li><a href=\"/\" class=\"nuxt-link-active\">Index</a></li> <li><a href=\"/page-a\">Page A - only logged in user</a></li> <li><a href=\"/page-b\">Page B</a></li></ul> <div><div></div><div></div></div></div></div></div><script>window.__NUXT__={layout:\"default\",data:[{}],error:null,serverRendered:true,apollo:{defaultClient:{}}};</script><script src=\"/_nuxt/01600d5cf8307d1ab639.js\" defer></script><script src=\"/_nuxt/9d11ee4e407907c05ac6.js\" defer></script><script src=\"/_nuxt/b9bb5b781e3c2a6d7fe1.js\" defer></script><script src=\"/_nuxt/285f2c1bb56f8b0be417.js\" defer></script><script src=\"/_nuxt/9a34682f8a0f01ce86f3.js\" defer></script>
  </body>
</html>
"

  27 |   test('normalQuery', async () => {
  28 |     const html = await get('/normalQuery')
> 29 |     expect(html).toContain('cjw1jhoxi1f4g0112ayaq3pyz')
     |                  ^
  30 |   })
  31 | 
  32 |   test('asyncData', async () => {

  at Object.toContain (test/module.test.js:29:18)```
gino

gino posted a new question

apollo-module •

Token expiry / refresh tokens

Hi,

Access tokens are usually, cause of safety purposes, set to have an expiration date. For example, an access token expires after 30 minutes and a refresh token will be used to generate a new access token. Unfortunately I do not see how I am able to achieve this. It looks like it is necessary to have an access token with no expiration or is it possible to achieve this with refresh tokens?

Cause my access token obviously expires after ~30 minutes, and I do not wanna force the user to login every 30 minutes. And I do not wanna create an access token that has no expiration date at all, this would not be safe.

Is there anyone else that is experiencing the same issue and knows how I am able to fix this?

Thanks a lot.

m2sahin

m2sahin posted a new question

apollo-module •

graphql subscription does not work when the page is not open

hi,
I have a problem and haven't found the solution for days. My English is not good, I hope I can explain the problem.

Now imagine a nuxt application and three different pages. Create post page, post list page and homepage. The page where the posts are listed is written graphql subscription code. first I opened the page where the posts are listed. I opened the create post page in another tab and created a new post. The post I created was listed instantly on the open page, so subscription code is works.

now in the first tab i open the home page (client side render), the other tab the create post page is still open. I created a new post in the second tab. then i opened the post list page in the first tab (client side render). No new post has been added. So the subsicription code didn't work. Listening is stopped while another page is open. how can i solve this problem

thanks

kampfkuchen

kampfkuchen posted a new question

apollo-module •

Authorization header not set on login

I am trying to create a login functionality using nuxtjs with the nuxtjs apollo-module and nodejs in the backend using apollo-server. I would like to pass the token from the frontend (nuxtjs/apollo-client) to the backend (nodejs/apollo-server).


Signin Function (frontend)

async signin () {
  const email = this.email
  const password = this.password
  try {
    const res = await this.$apollo.mutate({
      mutation: signIn,
      variables: {
        email,
        password
      }
    }).then(({ data }) => data && data.signIn)
    const token = res.token
    await this.$apolloHelpers.onLogin(token)
    this.$router.push('/feed')
  } catch (err) {
    // Error message
  }
}

nuxtjs.config (frontend)

apollo: {
clientConfigs: {
  default: {
    httpEndpoint: 'http://localhost:8000/graphql',
    wsEndpoint: 'ws://localhost:8000/graphql',
    authenticationType: 'Bearer',
    httpLinkOptions: {
      credentials: 'include'
    },
  }
}

Cookie in Browser DevTools


enter image description here

Index File (backend)

const app = express()

const corsConfig = {
  origin: 'http://127.0.0.1:3000',
  methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
  credentials: true
}

app.use(cors(corsConfig))

app.use(morgan('dev'))

const getMe = async req => {
  const token = req.headers.authorization // <========
  console.log(token) // returns 'Bearer undefined' 

  if (token) {
    try {
      return await jwt.verify(token, process.env.SECRET)
    } catch (e) {
      // Error message
    }
  }
}

const server = new ApolloServer({
  introspection: true,
  playground: true,
  typeDefs: schema,
  resolvers,
  context: async ({ req }) => {    
    if (req) {
      const me = await getMe(req)

      return {
        models,
        me,
        secret: process.env.SECRET,
        loaders: {
          user: new DataLoader(keys =>
            loaders.user.batchUsers(keys, models),
          ),
        },
      }
    }
  },
})

server.applyMiddleware({
  app,
  path: '/graphql',
  cors: false
})

const httpServer = http.createServer(app)
server.installSubscriptionHandlers(httpServer)

const port = process.env.PORT || 8000

sequelize.sync({ force: true }).then(async () => {
  createUsers(new Date())

  httpServer.listen({ port }, () => {
    console.log(`Apollo Server on http://localhost:${port}/graphql`)
  })
})



The token is saved in a cookie called 'apollo-token'. However the Authorization header in the format 'Bearer token' is not set. According to the apollo-client documentation this should be set automatically (https://github.com/nuxt-community/apollo-module#authenticationtype-string-optional-default-bearer).


What am I missing? I would be very thankful for any kind of help!

mlsen

mlsen posted a new bug report

apollo-module •

bug Mismatching childNodes vs. VNodes

Version

4.0.1-rc.3

Reproduction link

https://github.com/mlsen/nuxt-apollo-report

Steps to reproduce

  1. yarn install
  2. yarn dev
  3. Visit the index page and have a look at the console

What is expected ?

No errors and data being loaded on the server (SSR)

What is actually happening?

It's giving me a warning

Mismatching childNodes vs. VNodes

and an error

The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render.

The data is then fetched on the client again.

This only happens using the "apollo" object in my component, asyncData works fine.

David-Wennemaring

David-Wennemaring posted a new question

apollo-module •

Read Fragment of optimistic Response

What I try to do

  • I have an app which should work offline.
  • There is an Item-list. I can add an Item to this list with a mutation.
  • The update function of the mutation adds the Item to the Item-list.
  • When I click on an Item, I want to see the details.

My Implementation

Content of Mutation update function:

  const queryData = cache.readQuery<{ items: Item[] }>({
    query: MY_QUERY,
    variables: {
      filter
    }
  });
  if (!queryData?.items) {
    return;
  }
  const newData = [...queryData.items, newItem];
  cache.writeQuery({
    query: MY_QUERY,
    data: { items: newData },
    variables: {
      filter
    }
  });

Get details of the item in the vue-file:

apolloProvider.clients.defaultClient
      .readFragment<Item>({
        fragment: ITEM_FRAGMENT,
        id:id
      });

The problem

Adding the item to the Query-result works fine.
When I try to read the fragment:

  1. I get null for items which were added by the Mutation update function
  2. I get the expected object for items which were fetched from the backend
    There is also the optimistic attribute in readFragment, but that doesn't make a difference.

Other observations

When I write and immediately read the fragment in the Mutation update function, I am able to get it.

  cache.writeFragment({
    fragment: ITEM_FRAGMENT,
    data: item,
    id: item._id,
  });
  const data = cache.readFragment({
    fragment: ITEM_FRAGMENT,
    id: item._id,
  });
  console.log({ data }); // This logs my item Object

Versions I use:

{
"@nuxtjs/apollo": "^4.0.1-rc.3",
"apollo-cache-persist": "^0.1.1",
"nuxt": "^2.0.0",
}

Summary

I apollo.readFragement doesn't work for values from an optimistic response.

Question

Is this expected behaviour, is there something wrong with the implementation, or is it a bug?

If required, I will try to create short example to reproduce this issue.

rsfarias

rsfarias posted a new question

apollo-module •

Middlewares keep being called every few seconds

After installing Nuxt Apollo, middlewares get called every few seconds.

To replicate the behaviour, simply add a console.log in any middleware, or in the getAuth() function of Apollo's config file.

If the module is removed from the nuxt.config.js file, the loop stops.

Does anyone know how to stop this loop? Is this a bug or intentional?

madsh93

madsh93 posted a new question

apollo-module •

Unable to access elements in array

Hi

I am currently having an issue where I e.g. can't use articles[0].title but I have to use a v-for to loop through and thereby use article.title.

2020-08-20 09_51_06-Window.png

I've tried adding index to the v-for to make sure I am not hitting the wrong index. I have also tested directly in the graphql playground (using strapi)

My code looks like this:
2020-08-20 09_52_48-Window.png

What am I doing wrong here? Can anybody help me?

sharoneh

sharoneh posted a new bug report

apollo-module •

bug fetchPolicy no-cache config not working

Version

v4.0.1-rc.1

Reproduction link

https://stackoverflow.com/questions/57415569/nuxt-js-apollo-client-how-to-disable-cache

Steps to reproduce

I'm calling the query and mutation methods inside vuex actions, through this.app.apolloProvider.defaultClient

After making a mutation, I dispatch another action querying the updated data but the nuxt page would display the old data still, and the request wasn't displayed in the network tab of devtools.
I'd have to reload the whole page in the browser to get the client to fetch the new data.

I disabled the caching in nuxt.config.js as documented but the problem wasn't solved.

After several days searching for solutions, I finally found this answer in stackoverflow that saved me. After setting the fetchPolicy to 'no-cache' in a plugin, the problem was finally solved.

What is expected ?

Setting fetchPolicy to 'no-cache' in nuxt.config.js should work.

What is actually happening?

The fetchPolicy configuration in nuxt.config.js isn't working, I had to override it using a plugin.

euller88

euller88 posted a new question

apollo-module •

Nuxt, apolloProvider, code completion and typescript

The vue-apollo package includes a definition of apolloProvider in its definitions files, so we can find it by the code completion feature of code editors whenever we need something outside of the dollar field of the vue instance. But this package, even though it works flawlessly, seems to not expose apolloProvider, even when I include it in the types section of the compiler options in the tsconfig.json file. Is there another step of configuration that I'm not aware of? Or this package does not have this defined?

P.S.: putting vue-apollo in the tsconfig.json does solve the lack of code completion, but it is not a intuitive solution, nor is documented in any of the places that I've looked.

frt93

frt93 posted a new question

apollo-module •

how to transfer or restore apollo ssr cache on client

I checked this issues:
https://github.com/nuxt-community/apollo-module/issues/286
https://github.com/nuxt-community/apollo-module/pull/290

but i can't restore cache from nuxtServerInit's request on the client

frt93

frt93 posted a new question

apollo-module •

User authentication cases

I faced with uncertainty how to properly organize user authentication and authorization.

I'm using hasura as graphql engine. I make a request for user data, as a result an action is triggered, which, using a webhook, receives user data on express server, generates an access token based on them and refresh token, puts the refresh token in the httpl-only cookie and sends all this to the client. And on the client, the access token must be set in the apollo authorization header. I also intend to use this access token in the authorization middleware to protect some pages from guests. But:

1) If i using smart query in auth component, i haven't access to "this" in update or result hook and can't use $apolloHelpers. In addition middleware triggers before smartQuery update or result hooks and the user in such a case is not authenticated on the page render
2) I can use the nuxtServerInit for this purpose, but in this case, on the client, I don't have access to the user data from the ssr cache, since they are cleared. And I will either have to duplicate the request for user data to further manipulate it, or store and manipulate the user instance using vuex, which will be a double source of truth

janeschindler

janeschindler posted a new question

apollo-module •

defaultClient undefined in nuxt store

I have an async function in the store that gets events from a third party using await this.$axios.get(). Any page that calls this function (via fetch and store.dispatch in page template) fails on reload. If you navigate there from another page, ti works great. But if you go directly to the page, it fails with the message "TypeError: Cannot read property 'defaultClient' of undefined". There is a 404 error, but instead of directing to our 404 page, I get nothing with this message. In fact, any wrong url (/asdf) fails this way instead of giving our 404 page. I actually don't understand why apollo is involved at all. Does anyone else? The live site is here: https://stapferhaus.ch/agenda. Thanks for any ideas of what to check.