简体   繁体   English

nuxt.config.js 中的 Apollo 查询

[英]Apollo query inside nuxt.config.js

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).我正在尝试使用nuxt-apollo-modulenuxt中发出智能请求,以便获取nuxt-sitemaps-module的路线(这样我就可以用它们创建我的站点地图)。

I need to make this request from within nuxt.config.js file.我需要从nuxt.config.js文件中发出这个请求。 I have tried this way with no luck (as app doesn't exist in this context).我尝试过这种方式但没有运气(因为app在这种情况下不存在)。 What would be the right way to do this?这样做的正确方法是什么? Thanks in advance!提前致谢!

The relevant part of my nuxt.config.js我的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]
    }
  }
}

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
  },
},

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/按照这里有一个 Vue 示例的文档来了解它: 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?如果您还可以使用 auth,使用 apollo-boost 可能是一种更简洁的方法?

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)
}

I gave up using Apollo.我放弃了使用 Apollo。 It was easier to use Axios.使用 Axios 更容易。 Moreover, no nneds to configure @nuxtjs/sitemap:此外,无需配置@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
        })
    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM