1
- import { GraphQLServer , PubSub } from 'graphql-yoga' ;
1
+ import { createPubSub , createSchema , createYoga } from 'graphql-yoga'
2
+ import { createServer } from 'node:http'
3
+ import { useServer } from 'graphql-ws/lib/use/ws'
4
+ import { WebSocketServer } from 'ws'
5
+ import * as fs from 'fs'
2
6
import db from './db' ;
3
7
import Query from './resolvers/Query' ;
4
8
import Mutation from './resolvers/Mutation' ;
@@ -7,24 +11,74 @@ import User from './resolvers/User';
7
11
import Post from './resolvers/Post' ;
8
12
import Comment from './resolvers/Comment' ;
9
13
10
- const pubsub = new PubSub ( ) ;
11
-
12
- const server = new GraphQLServer ( {
13
- typeDefs : './src/schema.graphql' ,
14
- resolvers : {
15
- Query,
16
- Mutation,
17
- Subscription,
18
- User,
19
- Post,
20
- Comment,
21
- } ,
14
+ const pubsub = createPubSub ( ) ;
15
+
16
+ const yoga = createYoga ( {
17
+ schema : createSchema ( {
18
+ typeDefs : fs . readFileSync (
19
+ './src/schema.graphql' ,
20
+ 'utf-8'
21
+ ) ,
22
+ resolvers : {
23
+ Query,
24
+ Mutation,
25
+ Subscription,
26
+ User,
27
+ Post,
28
+ Comment,
29
+ } ,
30
+ } ) ,
22
31
context : {
23
32
db,
24
33
pubsub,
25
34
} ,
35
+ // graphqlEndpoint: '/', // uncomment this to send the app to: 4000/
36
+ graphiql : {
37
+ subscriptionsProtocol : 'WS' ,
38
+ } ,
26
39
} ) ;
27
40
28
- server . start ( { port : process . env . PORT | 5000 } , ( ) => {
29
- console . log ( `The server is up on port ${ process . env . PORT | 5000 } !` ) ;
41
+ const server = createServer ( yoga )
42
+
43
+ const wsServer = new WebSocketServer ( {
44
+ server : server ,
45
+ path : yoga . graphqlEndpoint ,
46
+ } )
47
+
48
+ useServer (
49
+ {
50
+ execute : ( args ) => args . rootValue . execute ( args ) ,
51
+ subscribe : ( args ) => args . rootValue . subscribe ( args ) ,
52
+ onSubscribe : async ( ctx , msg ) => {
53
+ const { schema, execute, subscribe, contextFactory, parse, validate } =
54
+ yoga . getEnveloped ( {
55
+ ...ctx ,
56
+ req : ctx . extra . request ,
57
+ socket : ctx . extra . socket ,
58
+ params : msg . payload
59
+ } )
60
+
61
+ const args = {
62
+ schema,
63
+ operationName : msg . payload . operationName ,
64
+ document : parse ( msg . payload . query ) ,
65
+ variableValues : msg . payload . variables ,
66
+ contextValue : await contextFactory ( ) ,
67
+ rootValue : {
68
+ execute,
69
+ subscribe
70
+ }
71
+ }
72
+
73
+ const errors = validate ( args . schema , args . document )
74
+ if ( errors . length ) return errors
75
+ return args
76
+ } ,
77
+ } ,
78
+ wsServer ,
79
+ )
80
+
81
+ const port = process . env . PORT || 4000 ;
82
+ server . listen ( { port} , ( ) => {
83
+ console . log ( `The server is up on port ${ port } !` ) ;
30
84
} ) ;
0 commit comments