vue.js nuxt.config.js内的Apollo查询

6kkfgxo0  于 2022-12-14  发布在  Vue.js
关注(0)|答案(2)|浏览(151)

我试图在nuxt中用nuxt-apollo-module发出一个智能请求,以便为nuxt-sitemaps-module获取我的路径(这样我就可以用它们创建我的站点Map)。
我需要在nuxt.config.js文件中进行此请求。我尝试过这种方法,但没有成功(因为app在此上下文中不存在)。什么是正确的方法?提前感谢!
我的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]
    }
  }
}
lymgl2op

lymgl2op1#

我可以用这种方式生成它,但我相信还有更好的方法。
第一个

6g8kf2rb

6g8kf2rb2#

这就是我如何能够做到这一点与身份验证。得到了它的以下文档在这里有一个Vue的例子:https://www.apollographql.com/docs/react/networking/authentication/
如果你也可以使用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)
}

相关问题