-
Notifications
You must be signed in to change notification settings - Fork 108
-
graphql-yoga is a popular GraphQL server, and it primary handles subscriptions via Server Sent Events, not WebSockets. Unfortunately, there is no easy way to currently get this working with graphql-zeus. However, there is a nice library @microsoft/fetch-event-source that treats EventSource more like a fetch method.
Would it make sense to add a plugin that exposes something like this:
import { fetchEventSource } from '@microsoft/fetch-event-source'
export const subscribe = (query: SomeObject, onMessage: (update: SomeUpdate) => void) =>
fetchEventSource(`${schemaUrl}?query=${turnQueryObjIntoString(query)}`, {
onmessage: (d) => {
onMessage(JSON.parse(d) as SomeUpdate)
}
})
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 2 comments
-
For example, here's a React hook that will subscribe to EventSource updates and automatically update an entry in a react-query cache:
import { QueryKey, useQueryClient } from '@tanstack/react-query'
import { Zeus, ValueTypes } from '../zeus'
import deepmerge from 'deepmerge'
export const useSubscription = (queryKey: QueryKey, shape: ValueTypes['Subscription']) => {
const queryClient = useQueryClient()
const shapeString = Zeus('subscription', shape)
useEffect(() => {
fetchEventSource(`${HOST}?query=${encodeURIComponent(shapeString)}`, {
onmessage: (ev) => {
// TODO: typing, error handling
const newData = JSON.parse(ev.data).data as {}
const oldData = queryClient.getQueryData(queryKey) as {}
queryClient.setQueryData(queryKey, deepmerge(oldData, newData))
}
})
}, [])
}
Beta Was this translation helpful? Give feedback.
All reactions
-
I think we have graphql-ws subscription support also. Right now it is very complicated to use our legacy protocol but sometimes it is the only things that work.?
But DX should be improved there a lot.
Beta Was this translation helpful? Give feedback.