1
1
import { type AddressInfo } from 'node:net' ;
2
- import Fastify , { type FastifyInstance } from 'fastify' ;
2
+ import Fastify , {
3
+ type FastifyInstance ,
4
+ type FastifyReply ,
5
+ type FastifyRequest ,
6
+ } from 'fastify' ;
7
+ import { createSchema , createYoga } from 'graphql-yoga' ;
3
8
import { describe , test , expect , beforeAll , afterAll } from 'vitest' ;
4
9
import { FetchHttpClient } from './fetch-http-client' ;
5
10
@@ -18,6 +23,35 @@ describe('FetchHttpClient', () => {
18
23
await reply . send ( { hello : 'world' } ) ;
19
24
} ) ;
20
25
26
+ const yoga = createYoga < {
27
+ req : FastifyRequest ;
28
+ reply : FastifyReply ;
29
+ } > ( {
30
+ schema : createSchema ( {
31
+ typeDefs : /* GraphQL */ `
32
+ type Query {
33
+ item(id: Int): String
34
+ }
35
+ ` ,
36
+ resolvers : { Query : { item : ( ) => 'success' } } ,
37
+ } ) ,
38
+ } ) ;
39
+
40
+ fastify . route ( {
41
+ url : '/graphql' ,
42
+ method : 'POST' ,
43
+ handler : async ( req , reply ) => {
44
+ const response = await yoga . handleNodeRequest ( req , {
45
+ req,
46
+ reply,
47
+ } ) ;
48
+ void reply . status ( response . status ) ;
49
+ void reply . send ( response . body ) ;
50
+
51
+ return await reply ;
52
+ } ,
53
+ } ) ;
54
+
21
55
await fastify . listen ( { port : 0 } ) ;
22
56
} ) ;
23
57
@@ -38,6 +72,30 @@ describe('FetchHttpClient', () => {
38
72
expect ( await response . json ( ) ) . toEqual ( { hello : 'world' } ) ;
39
73
} ) ;
40
74
75
+ test ( 'should request graphql successfully' , async ( ) => {
76
+ // given
77
+ const address = fastify . server . address ( ) as AddressInfo ;
78
+ const httpClient = new FetchHttpClient ( 5000 ) ;
79
+ const request = new Request ( `http://localhost:${ address . port } /graphql` , {
80
+ method : 'POST' ,
81
+ headers : { 'Content-Type' : 'application/json' } ,
82
+ body : JSON . stringify ( {
83
+ query : /* GraphQL */ `
84
+ query item($id: Int!) {
85
+ item(id: $id)
86
+ }
87
+ ` ,
88
+ variables : { id : 1 } ,
89
+ } ) ,
90
+ } ) ;
91
+
92
+ // when
93
+ const response = await httpClient . request ( request ) ;
94
+
95
+ // then
96
+ expect ( await response . json ( ) ) . toEqual ( { data : { item : 'success' } } ) ;
97
+ } ) ;
98
+
41
99
test ( 'should throw error when timeout' , async ( ) => {
42
100
// given
43
101
const address = fastify . server . address ( ) as AddressInfo ;
0 commit comments