Documentation
Modules
use/bun

Module: use/bun

Interfaces

Other

handleProtocols

Re-exports handleProtocols

Server/bun

makeHandler

makeHandler<P, E>(options): WebSocketHandler

Use the server with Bun. This is a basic starter, feel free to copy the code over and adjust it to your needs

The WebSocket subprotocol is not available on the established socket and therefore needs to be checked during the request handling.

Additionally, the keep-alive logic seems to be handled by Bun seeing that they default sendPingsAutomatically to true.

import { makeHandler, handleProtocols } from 'graphql-ws/lib/use/lib/bun';
import { schema } from './my-schema';
 
Bun.serve({
  fetch(req, server) {
    const [path, _search] = req.url.split('?');
    if (!path.endsWith('/graphql')) {
      return new Response('Not Found', { status: 404 });
    }
    if (req.headers.get('upgrade') != 'websocket') {
      return new Response('Upgrade Required', { status: 426 });
    }
    if (!handleProtocols(req.headers.get('sec-websocket-protocol') || '')) {
      return new Response('Bad Request', { status: 404 });
    }
    if (!server.upgrade(req)) {
      return new Response('Internal Server Error', { status: 500 });
    }
    return new Response();
  },
  websocket: makeHandler({ schema }),
  port: 4000,
});
 
console.log('Listening to port 4000');

Type parameters

NameType
Pextends undefined | Record<string, unknown> = undefined | Record<string, unknown>
Eextends Record<PropertyKey, unknown> = Record<PropertyKey, never>

Parameters

NameType
optionsServerOptions<P, Extra & Partial<E>>

Returns

WebSocketHandler

Defined in

src/use/bun.ts:67