Skip to content

Commit

Permalink
Ping/pong for SSE (#2150)
Browse files Browse the repository at this point in the history
* Ping/pong for SSE

* Update packages/graphql-yoga/src/plugins/resultProcessor/push.ts

Co-authored-by: Denis Badurina <badurinadenis@gmail.com>

Co-authored-by: Denis Badurina <badurinadenis@gmail.com>
  • Loading branch information
ardatan and enisdenjo committed Dec 26, 2022
1 parent a2dd6bc commit 290c7f7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/wise-geckos-beam.md
@@ -0,0 +1,5 @@
---
'graphql-yoga': minor
---

Ping the client every 12 seconds to keep the connection alive
16 changes: 15 additions & 1 deletion packages/graphql-yoga/src/plugins/resultProcessor/push.ts
Expand Up @@ -9,6 +9,8 @@ export function processPushResult(
result: ResultProcessorInput,
fetchAPI: FetchAPI,
): Response {
const timeoutInSeconds = 12

const headersInit = {
'Content-Type': 'text/event-stream',
Connection: 'keep-alive',
Expand All @@ -20,9 +22,19 @@ export function processPushResult(

let iterator: AsyncIterator<MaybeArray<ExecutionResult>>

let pingInterval: number
const textEncoder = new fetchAPI.TextEncoder()
const readableStream = new fetchAPI.ReadableStream({
start() {
start(controller) {
// ping client every 12 seconds to keep the connection alive
pingInterval = setInterval(() => {
if (!controller.desiredSize) {
clearInterval(pingInterval)
return
}
controller.enqueue(textEncoder.encode(':\n\n'))
}, timeoutInSeconds * 1000) as unknown as number

if (isAsyncIterable(result)) {
iterator = result[Symbol.asyncIterator]()
} else {
Expand All @@ -45,10 +57,12 @@ export function processPushResult(
controller.enqueue(textEncoder.encode(`data: ${chunk}\n\n`))
}
if (done) {
clearInterval(pingInterval)
controller.close()
}
},
async cancel(e) {
clearInterval(pingInterval)
await iterator.return?.(e)
},
})
Expand Down

0 comments on commit 290c7f7

Please sign in to comment.