我能够通过 https ( https://dev.to/dmitryame/getting-apollo-client-to-work-with-awssubscribe-494i ) 获得 aws AppSync graphql 订阅,但是,这种方法不可靠且不连续断开连接。现在,我正在尝试弄清楚如何实现 WebSocket 版本。
我的客户是一个 react-native 应用程序。我不想使用任何特殊的钩子——我只想让原始订阅与 API_KEY 一起工作。
这是我通过 WebSocket 建立与 AppSync 的 API_KEY 身份验证连接的代码:
import Constants from 'expo-constants'
import base64 from 'react-native-base64'
import { WebSocketLink } from "@apollo/client/link/ws"
import { ApolloClient, InMemoryCache } from "@apollo/client"
const {
API_URI, REALTIME_API_URI, API_KEY
} = Constants.manifest.extra
const HOST = API_URI.replace('https://', '').replace('/graphql', '')
const api_header = {
host: HOST,
'x-api-key': API_KEY,
}
const header_encode = obj => base64.encode(JSON.stringify(obj))
const connection_url = `${REALTIME_API_URI}?header=${header_encode(api_header)}&payload=${header_encode({})}`
console.log({ connection_url })
const wsLink = new WebSocketLink({
uri: connection_url,
options: {
reconnect: true,
lazy: true,
connectionCallback: (error, result) => {
console.log("connectionCallback", error ? "ERR" : "OK", { error, result })
},
},
})
const subscriptionClient = new ApolloClient({
cache: new InMemoryCache(),
link: wsLink,
})
export default subscriptionClient
我知道,这种建立连接的方法是有效的,因为如果我开始使用 HOST 和 API_KEY 进行修改,我会收到 400 错误,否则似乎连接没有问题。
但是,通过此连接进行的订阅永远不会触发 Observable 的任何方法。这是代码:
useEffect(() => {
console.log(`subscribing to ${chatUuid}`)
// add subscription listener
const observableObject = subscriptionClient
.subscribe({
query: gql`
subscription onSendMessage($chatUuid: String!) {
onSendMessage (chatUuid: $chatUuid) {
chatUuid
createdAt
messageUuid
text
pending
chatPhotoUuid
updatedAt
uuid
}
}`,
variables: {
chatUuid,
},
})
// console.log({ observableObject })
const subscription = observableObject.subscribe({
next(data) {
console.log({ data }) // never see this in the log
},
error(error) {
console.error("subscription error", { error }) // never see this in the log
},
complete() {
console.log("subs. DONE") // never see this in the log
},
})
return () => {
subscription.unsubscribe()
console.log(`unsubscribing from ${chatUuid}`)
}
}, [])// eslint-disable-line react-hooks/exhaustive-deps
console.log in next、error 和 complete 永远不会触发。订阅在 AppSync 中正确定义——我看到它在 AWS 控制台中工作。我在这里想念什么?