4

I'm trying to make a smart request in nuxt with nuxt-apollo-module in order to grab my routes for the nuxt-sitemaps-module (so I can create my sitemap with them).

I need to make this request from within nuxt.config.js file. I have tried this way with no luck (as app doesn't exist in this context). What would be the right way to do this? Thanks in advance!

The relevant part of my nuxt.config.js

import gql from 'graphql-tag'

module.exports = {

  modules: [
    '@nuxtjs/apollo',
    '@nuxtjs/sitemap'
  ],

  apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: 'https://example.com/graphql'
      }
    }
  },


  sitemap: {
    path: '/sitemap.xml',
    hostname: 'https://example.com/',
    generate: true,
    cacheTime: 86400,
    trailingSlash: true,
    routes: async ({ app }) => {
      const myRoutes = ['/one-random-path/']
      let client = app.apolloProvider.defaultClient
      let myProductsQuery = gql`query {
          products {
              slug
          }
      }`
      let myBrandsQuery = gql`query {
          brands {
              slug
          }
      }`
      const myProducts = await client.query({ query: myProductsQuery })
      const myBrands = await client.query({ query: myBrandsQuery })

      return [myRoutes, ...myProducts, ...myBrands]
    }
  }
}
Jonathan Irwin
  • 5,009
  • 2
  • 29
  • 48
Joe82
  • 1,357
  • 2
  • 24
  • 40
  • I'll digg into it, but is there a way you could use nuxtServerInit Aswell, will it be a static site ? spa or ssr ? – DarioRega Nov 25 '20 at 10:10
  • SSR, but I will probably port it to netlify at some point. So far I have it working SSR with the sitemap generator, the only difference is that the requests were made with axios ( `import axios from 'axios'` and then used `axios.get` – Joe82 Nov 25 '20 at 13:10
  • Can't you moove to action other part than nuxt conifg? – DarioRega Nov 25 '20 at 19:17
  • Nope, that's the tricky part. I have to set the routes of the sitemap-module in the nuxt.config.js file – Joe82 Nov 25 '20 at 20:30
  • do you have a github repo i could take a look locally ? – DarioRega Nov 25 '20 at 20:31
  • yep, sure, send me your mail and I'll add you to my gitlab – Joe82 Nov 25 '20 at 21:09
  • I've just read this answer, maybe it could help [Access to this.$apollo from Vuex store with vue-apollo in NUXT?](https://stackoverflow.com/a/65630793) – Carlos Fuentes Feb 03 '21 at 17:42
  • Hi @CarlosFuentes, thanks for the message. The post you point helps you to have apollo in vuex store, but this is not the store, but the config file (nuxt.config.js) – Joe82 Feb 04 '21 at 10:35
  • 1
    Hi @joe82, i'm the nuxt sitemap module creator. You cannot use a Nuxt module directly from the `nuxt.config.js` script (see this Nuxt core member answer https://github.com/nuxt-community/axios-module/issues/242#issuecomment-544923463) – Nicolas Pennec Feb 15 '21 at 10:15

3 Answers3

3

I was able to generate it this way, but I'm sure there is a better way.

yarn add node-fetch apollo-boost
sitemap: {
  routes: async () => {
    const routes = []
    const fetch = require("node-fetch")
    const { gql } = require("apollo-boost")
    const ApolloBoost = require("apollo-boost")
    const ApolloClient = ApolloBoost.default

    const client = new ApolloClient({
      fetch: fetch,
      uri: YOUR_API_ENDPOINT,
    })

    const fetchUsers = gql`
      query {
        users {
          id
        }
      }
    `

    const users = await client
      .query({
        query: fetchUsers,
      })
      .then((res) => res.data.users)

    users.forEach((user) => {
      routes.push({
        route: `/${user.id}`,
      })
    })

    return routes
  },
},
1

I gave up using Apollo. It was easier to use Axios. Moreover, no nneds to configure @nuxtjs/sitemap :

import axios from 'axios'

sitemap: {
    hostname: URL_SITE,
    gzip: true,
},
routes() {
    return axios({
        url: ENDPOINT,
        method: 'post',
        data: {
            query: `
                query GET_POSTS {
                    posts {
                        nodes {
                            slug
                        }
                    }
                }
            `,
        },
    }).then((result) => {
        return result.data.data.posts.nodes.map((post) => {
            return '/blog/' + post.slug
        })
    })
}
Paidge
  • 11
  • 2
0

This was how I was able to do it with authentication. Got round to it by following the documentation here which had a Vue example: https://www.apollographql.com/docs/react/networking/authentication/

Might be a cleaner way to do it with apollo-boost if you can also use auth?

import fetch from 'node-fetch'
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { ApolloLink, concat } from 'apollo-link'
import { InMemoryCache } from 'apollo-cache-inmemory'

import globalQuery from './apollo/queries/global.js'

const httpLink = new HttpLink({ uri: process.env.SCHEMA_URL, fetch })

const authMiddleware = new ApolloLink((operation, forward) => {
  // add the authorization to the headers
  const token = process.env.STRAPI_API_TOKEN
  operation.setContext({
    headers: {
      authorization: token ? `Bearer ${token}` : 'Bearer',
    },
  })
  return forward(operation)
})

export const apolloClient = new ApolloClient({
  link: concat(authMiddleware, httpLink),
  cache: new InMemoryCache(),
})

export default async () => {
  let global = null
  const globalResponse = await apolloClient.query({ query: globalQuery })
  if (globalResponse?.data?.global?.data) {
    global = globalResponse.data.global.data.attributes
  }

  console.log('globals:::', global)
}
Quibble
  • 21
  • 1