@@ -17,13 +17,66 @@ You can follow the introduction page directly to use Hive Gateway CLI. [See here
1717Use this method only if you know what you are doing. It is recommended to use Hive Gateway CLI for
1818most cases.
1919
20- ``` ts
20+ ``` ts filename="index.ts"
2121import { createServer } from ' http'
2222import { createGatewayRuntime } from ' @graphql-hive/gateway-runtime'
23+ import { enableWebSocket } from ' ./websocket.ts'
2324
24- const serveRuntime = createGatewayRuntime (/* Your configuration */ )
25+ // Create the gateway runtime. The Gateway Runtime is an http handler.
26+ const serveRuntime = createGatewayRuntime ({
27+ /* Your configuration */
28+ })
29+
30+ // Create the HTTP server that will listen for incoming HTTP requests.
31+ // It can be any server implementation, here we use Node official http module.
2532const server = createServer (serveRuntime )
33+
34+ // Optionally add support for WebSockets, see below for details
35+ enableWebSocket (server , serverRuntime )
36+
2637server .listen (4000 , () => {
2738 console .log (` Server is running on http://localhost:4000 ` )
2839})
2940```
41+
42+ ## WebSocket support
43+
44+ To enable WebSocket support, you have to configure ` graphql-ws ` to be used to handle incoming
45+ WebSockets.
46+
47+ Here is an example of how to do it with Node server, but it can be used with most server
48+ implementations (see
49+ [ ` graphql-ws ` documentation for more details] ( https://the-guild.dev/graphql/ws/recipes#server ) ).
50+
51+ Use ` getGraphQLWSOptions ` from ` @graphql-hive/gateway-runtime ` to automatically generate the
52+ ` graphql-ws ` configuration for your runtime. Adapt the ` onContext ` parameter with your HTTP server
53+ specific needs.
54+
55+ ``` ts filename="websocket.ts"
56+ import type { Server } from ' node:http'
57+ import { useServer } from ' graphql-ws/use/ws'
58+ import { WebSocketServer } from ' ws'
59+ import { GatewayRuntime , getGraphQLWSOptions } from ' @graphql-hive/gateway-runtime'
60+
61+ function enableWebSocket(server : Server , runtime : GatewayRuntime ): void {
62+ const wsServer = new WebSocketServer ({
63+ path: runtime .graphqlEndpoint ,
64+ server
65+ })
66+
67+ useServer (
68+ getGraphQLWSOptions <TContext , Extra >(runtime , ctx => ({
69+ req: ctx .extra ?.request ,
70+ socket: ctx .extra ?.socket
71+ })),
72+ wsServer
73+ )
74+
75+ runtime .disposableStack .defer (
76+ () =>
77+ new Promise ((resolve , reject ) => {
78+ wsServer .close (err => (err ? reject (err ) : resolve ()))
79+ })
80+ )
81+ }
82+ ```
0 commit comments