Gomah / nuxt-graphql-request

Easy Minimal GraphQL client integration with Nuxt.js.
https://nuxt-graphql-request.vercel.app
MIT License
196 stars 16 forks source link

Using graphql request inside `generate` to request data for routes? #22

Closed alexmahan closed 3 years ago

alexmahan commented 3 years ago

This is more of a question than an issue. We're currently using nuxt-graphql-request in our project and it's working great.

However, we're looking to make a graphQL request in the generate property of the Nuxt config in order to generate routes based on the query response, something similar is outlined in this post which uses Apollo: https://rosso.codes/blog/nuxt-generate-dynamic-routes-with-apollo-and-graphql/

Wondering if there's a way to reference/access the graphql property created in the Nuxt config INSIDE another property in the config? Obviously we can't use this.$graphql inside the generate property.

Or perhaps there's a way to do this using middleware? Any thoughts welcome. Thanks!

Gomah commented 3 years ago

Hey @alexmahan, indeed, you can't use this.$graphql inside the generate property as, you have to use graphql-request like the following example:

import { request, gql } from 'graphql-request';

export default {
  generate: {
    routes() {
      const query = gql`
        {
          Movie(title: "Inception") {
            releaseDate
            actors {
              name
            }
          }
        }
      `;
      return request('https://api.graph.cool/simple/v1/movies', query).then(
        res => {
          return res.data.map(movie => {
            return {
              route: '/movies/' + movie.id,
              payload: movie,
            };
          });
        },
      );
    },
  },
};
drewbaker commented 3 years ago

@alexmahan i do want to point out that you don’t need to do any of this dynamic route stuff in the new versions of nuxt. It’s built in crawler will find the routes for you. Maybe you know this and are doing something differently here, but just a tip.

alexmahan commented 3 years ago

Thanks for the suggestions @Gomah @drewbaker! For some reason Nuxt isn't building those routes dynamically on generate for us, but perhaps we're doing something wrong. Will take another look.

andreasvirkus commented 3 years ago

Is there a way to source the query from an external file? Can't seem to get the .gql import working inside the config 😕

drewbaker commented 3 years ago

Yes. See here for an example: https://github.com/funkhaus/fuxt/blob/master/templates/page-default.vue

Check out the package file for that repo to see what you need for that to work.

andreasvirkus commented 3 years ago

Thanks for the reply! I have the queries working inside Vue files, but I'd need to include it in nuxt.config.js so I could use it in the generate.routes option