vue.js Nuxt:选择客户端配置而不是默认配置

ewm0tg9j  于 2023-08-07  发布在  Vue.js
关注(0)|答案(2)|浏览(137)

我正在使用Nuxt和Nuxt-Apollo创建我的Vue应用程序。我在nuxt.config.js文件中有以下apollo配置:

apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: 'http://localhost:8000/graphql/'
      },
      stage: {
        httpEndpoint: 'https://example-stage.com/graphql/'
      }
      prod: {
        httpEndpoint: 'https://example.com/graphql/'
      }
    }
  }

字符串
如何指向stageprod配置。每次我运行应用程序时,它都指向default配置。一定有地方可以设置的。

lztngnrs

lztngnrs1#

假设你正在尝试访问多个客户端,而不仅仅是一个不同的客户端的prod和dev,这可能会有所帮助,因为这是我用我目前的项目。

apollo: {
      includeNodeModules: true, // optional, default: false (this includes graphql-tag for node_modules folder)
      authenticationType: 'Basic', // optional, default: 'Bearer'
      errorHandler: '~/apollo/customErrorHandler',
      clientConfigs: {
      default:
         {
           httpEndpoint:
             'https://me.something.com/api/graphql/query?token=******',
           httpLinkOptions: {
             credentials: 'same-origin'
           }
         },
        //  '~/apollo/clientConfig.js',
      otherClient: {
        httpEndpoint:
          'https://second-endpoint-gql.herokuapp.com/v1/graphql',
        httpLinkOptions: {
          credentials: 'same-origin'
        }
      }
    }
  },

字符串
现在你需要做的就是让你的查询正常,但不同的是在vue组件。
/gql/allCars.gql

{
  allCars {
    id
    make
    model
    year
  }
}


调用default将像正常情况一样进行:

<script>
import allcars from '~/gql/users'
export default {
  apollo: {
    allcars: {
      prefetch: true,
      query: allcars
    }
  },
  filters: {
    charIndex (i) {
      return String.fromCharCode(97 + i)
    }
  },
  head: {
    title: ....
  },
  data () {
    return {
      ...
    }
  }
}
</script>


对辅助端点的调用需要添加$client:

<script>
import allcars from '~/gql/users'
export default {
  apollo: {
    $client: 'otherClient',
    allcars: {
      prefetch: true,
      query: allcars
    }
  },
  filters: {
    charIndex (i) {
      return String.fromCharCode(97 + i)
    }
  },
  head: {
    title: ....
  },
  data () {
    return {
      ...
    }
  }
}
</script>


apollo调试器似乎只查询apollo config中端点列表上的最后一个端点,在我的例子中是'otherClient',这一点毫无价值。
参考我是如何得出上述集成的:Vue multiple client

nbysray5

nbysray52#

如果您使用的是Pinia和Nuxt 3,您可以使用$apollo来选择所需的客户端:
假设“prod”客户端:

actions: {
  async someQuery (){
    const { $apollo } = useNuxtApp()

    const response = await $apollo.clients.prod.query({
        query: gql` YOUR_GQL_QUERRY  `,

        // you can add variables (OPTIONAL)
        variables: { YOUR_VARIABLES }
      })

     console.log(response.data)
  }
}

字符串
假设你已经设置了模块:'@nuxtjs/apollo'

相关问题