首页 > 解决方案 > 如何使用 Absinthe (Elixir) 和 Urql 进行 graphql 订阅?

问题描述

我的想法是使用 react 和 urql 构建一个客户端应用程序,以及使用 elixir 和苦艾酒构建一个 graphql api,但目前看起来它们并不能很好地结合在一起。

除了 Apollo 之外,有没有办法将 Absinthe 订阅实际用于任何其他客户端?我尝试使用 urql,但由于 ws 连接失败,出现以下错误:

WebSocket 连接到“ws://localhost:4000/socket/websocket”失败:WebSocket 握手期间出错:发送非空“Sec-WebSocket-Protocol”标头但未收到响应

到目前为止,我发现的唯一似乎与这个问题有关的是这个库 absinthe/socket-apollo-link (https://github.com/absinthe-graphql/absinthe-socket/tree/master/packages/socket -apollo-link)但它显然只适用于阿波罗。

在我失败的尝试中,我做了以下事情:

import React from 'react'
import { Provider, Client, dedupExchange, fetchExchange, subscriptionExchange } from 'urql'
import { cacheExchange } from '@urql/exchange-graphcache'
import { SubscriptionClient } from 'subscriptions-transport-ws'

const DataProvider = ({ children }) => {
  const cache = cacheExchange({})
  const subscriptionClient = new SubscriptionClient('ws://localhost:4000/socket/websocket', {})
  const client = new Client({
    url: 'http://localhost:4000/api',
    exchanges: [
      dedupExchange,
      cache,
      fetchExchange,
      subscriptionExchange({
        forwardSubscription: operations => subscriptionClient.request(operations),
      }),
    ],
  })
  return <Provider value={client}>{children}</Provider>
}

export default DataProvider

这个'subscriptions-transport-ws'我从一个教程中找到,并且在一些gh问题中提到了ws url末尾的神秘'/websocket',但它似乎有效(在将它添加到url末尾之前有根本没有ws连接)。

标签: websocketgraphql-subscriptionsabsintheurqlabsinthe-subscription

解决方案


这并不能直接回答问题,但如果有人最终遇到同样的困惑,并在此处回复您的评论:

我从教程中发现,在某些 gh 问题中提到了 ws url 末尾的神秘“/websocket”,但它似乎有效(在将其添加到 url 末尾之前,根本没有 ws 连接)。

这是因为 longpoll 和 websocket 都是可行的传输方式。你可能已经在你的中定义了你的套接字Endpointwebsocket: true它给了你这条路线。跑步mix phx.routes | grep socket将是一个有用的命令。


推荐阅读