1
1
import fastify , { RouteHandlerMethod } from "fastify" ;
2
2
import { parse as graphqlParse } from "graphql" ;
3
- import {
4
- getGraphQLParameters ,
5
- processRequest ,
6
- renderGraphiQL ,
7
- shouldRenderGraphiQL ,
8
- } from "../../lib" ;
3
+ import { getGraphQLParameters , processRequest , renderGraphiQL , sendResult , shouldRenderGraphiQL } from "../../lib" ;
9
4
import { schema } from "../schema" ;
10
5
11
- const sleep = ( time : number ) =>
12
- new Promise < void > ( ( resolve ) => setTimeout ( resolve , time ) ) ;
6
+ const sleep = ( time : number ) => new Promise < void > ( ( resolve ) => setTimeout ( resolve , time ) ) ;
13
7
14
8
const graphqlHandler : RouteHandlerMethod = async ( req , res ) => {
15
9
const request = {
@@ -31,57 +25,9 @@ const graphqlHandler: RouteHandlerMethod = async (req, res) => {
31
25
} ,
32
26
} ) ;
33
27
34
- if ( result . type === "RESPONSE" ) {
35
- result . headers . forEach ( ( { name, value } ) => res . header ( name , value ) ) ;
36
- res . status ( result . status ) ;
37
- res . send ( result . payload ) ;
38
- } else if ( result . type === "PUSH" ) {
39
- res . raw . writeHead ( 200 , {
40
- "Content-Type" : "text/event-stream" ,
41
- Connection : "keep-alive" ,
42
- "Cache-Control" : "no-cache" ,
43
- } ) ;
44
-
45
- req . raw . on ( "close" , ( ) => {
46
- result . unsubscribe ( ) ;
47
- } ) ;
48
-
49
- await result . subscribe ( ( result ) => {
50
- res . raw . write ( `data: ${ JSON . stringify ( result ) } \n\n` ) ;
51
- } ) ;
52
- } else {
53
- res . raw . writeHead ( 200 , {
54
- Connection : "keep-alive" ,
55
- "Content-Type" : 'multipart/mixed; boundary="-"' ,
56
- "Transfer-Encoding" : "chunked" ,
57
- } ) ;
58
-
59
- req . raw . on ( "close" , ( ) => {
60
- result . unsubscribe ( ) ;
61
- } ) ;
62
-
63
- res . raw . write ( "---" ) ;
64
-
65
- await result . subscribe ( ( result ) => {
66
- const chunk = Buffer . from ( JSON . stringify ( result ) , "utf8" ) ;
67
- const data = [
68
- "" ,
69
- "Content-Type: application/json; charset=utf-8" ,
70
- "Content-Length: " + String ( chunk . length ) ,
71
- "" ,
72
- chunk ,
73
- ] ;
74
-
75
- if ( result . hasNext ) {
76
- data . push ( "---" ) ;
77
- }
78
-
79
- res . raw . write ( data . join ( "\r\n" ) ) ;
80
- } ) ;
81
-
82
- res . raw . write ( "\r\n-----\r\n" ) ;
83
- res . raw . end ( ) ;
84
- }
28
+ await sendResult ( result , res . raw ) ;
29
+ // Tell fastify a response was sent
30
+ res . sent = true ;
85
31
} ;
86
32
87
33
const graphiqlHandler : RouteHandlerMethod = async ( _req , res ) => {
0 commit comments