簡體   English   中英

nuxt.config.js 中的 Apollo 查詢

[英]Apollo query inside nuxt.config.js

我正在嘗試使用nuxt-apollo-modulenuxt中發出智能請求,以便獲取nuxt-sitemaps-module的路線(這樣我就可以用它們創建我的站點地圖)。

我需要從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]
    }
  }
}

我能夠以這種方式生成它,但我確信有更好的方法。

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

這就是我能夠通過身份驗證做到這一點的方式。 按照這里有一個 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)
}

我放棄了使用 Apollo。 使用 Axios 更容易。 此外,無需配置@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