Skip to content

Commit

Permalink
fix: don't fail if graphql-ws is not installed
Browse files Browse the repository at this point in the history
  • Loading branch information
tobiasdiez committed Jul 9, 2024
1 parent a8ec8fe commit d209755
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
4 changes: 2 additions & 2 deletions examples/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ app.use(
'/ws',
startServerAndCreateH3Handler(apollo, {
websocket: {
...defineGraphqlWebSocket({ schema }),
...await defineGraphqlWebSocket({ schema }),
error(peer, error) {
console.error('[ws] error', peer, error)
// In a real app, you would want to properly log this error
Expand All @@ -90,7 +90,7 @@ app.use(
app.use(
'/_ws',
defineWebSocketHandler({
...defineGraphqlWebSocket({ schema }),
...await defineGraphqlWebSocket({ schema }),
error(peer, error) {
console.log('[ws] error', peer, error)
},
Expand Down
21 changes: 12 additions & 9 deletions src/websocket.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import {
makeServer,
import type {
ServerOptions,
ConnectionInitMessage,
GRAPHQL_TRANSPORT_WS_PROTOCOL,
ConnectionInitMessage
} from 'graphql-ws'
import {
defineWebSocket,
Expand Down Expand Up @@ -43,10 +41,15 @@ interface Client {
* Use this over {@link defineGraphqlWebSocketHandler} if you need more control over the WebSocket server or
* if you want to add custom hooks (e.g. for authentication or logging).
*/
export function defineGraphqlWebSocket<
export async function defineGraphqlWebSocket<
P extends ConnectionInitMessage['payload'] = ConnectionInitMessage['payload'],
E extends Record<PropertyKey, unknown> = Record<PropertyKey, never>,
>(options: ServerOptions<P, Extra & Partial<E>>): Partial<Hooks> {
>(options: ServerOptions<P, Extra & Partial<E>>): Promise<Partial<Hooks>> {
// Local import since graphql-ws is only an optional peer dependency
const {
makeServer,
GRAPHQL_TRANSPORT_WS_PROTOCOL,
} = await import('graphql-ws')
const server = makeServer(options)
const peers = new WeakMap<Peer, Client>()
return defineWebSocket({
Expand Down Expand Up @@ -104,11 +107,11 @@ export function defineGraphqlWebSocket<
*
* @category Server/h3
*/
export function defineGraphqlWebSocketHandler<
export async function defineGraphqlWebSocketHandler<
P extends ConnectionInitMessage['payload'] = ConnectionInitMessage['payload'],
E extends Record<PropertyKey, unknown> = Record<PropertyKey, never>,
>(
options: ServerOptions<P, Extra & Partial<E>>,
): EventHandler<EventHandlerRequest, never> {
return defineWebSocketHandler(defineGraphqlWebSocket(options))
): Promise<EventHandler<EventHandlerRequest, never>> {
return defineWebSocketHandler(await defineGraphqlWebSocket(options))
}

0 comments on commit d209755

Please sign in to comment.