-
Notifications
You must be signed in to change notification settings - Fork 559
/
push.ts
53 lines (49 loc) 路 1.41 KB
/
push.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { isAsyncIterable } from '@envelop/core'
import { ExecutionResult } from 'graphql'
import { encodeString } from '../../encodeString.js'
import { FetchAPI } from '../../types.js'
import { ResultProcessorInput } from '../types.js'
export function isPushResult(
request: Request,
result: ResultProcessorInput,
): result is AsyncIterable<ExecutionResult> {
return (
isAsyncIterable(result) &&
!!request.headers.get('accept')?.includes('text/event-stream')
)
}
export function processPushResult(
result: AsyncIterable<ExecutionResult>,
fetchAPI: FetchAPI,
): Response {
const headersInit: HeadersInit = {
'Content-Type': 'text/event-stream',
Connection: 'keep-alive',
'Cache-Control': 'no-cache',
'Content-Encoding': 'none',
}
const responseInit: ResponseInit = {
headers: headersInit,
status: 200,
}
let iterator: AsyncIterator<ExecutionResult<any>>
const readableStream = new fetchAPI.ReadableStream({
start() {
iterator = result[Symbol.asyncIterator]()
},
async pull(controller) {
const { done, value } = await iterator.next()
if (value != null) {
const chunk = JSON.stringify(value)
controller.enqueue(encodeString(`data: ${chunk}\n\n`))
}
if (done) {
controller.close()
}
},
async cancel(e) {
await iterator.return?.(e)
},
})
return new fetchAPI.Response(readableStream, responseInit)
}