fastify / fastify-websocket

basic websocket support for fastify
MIT License
394 stars 72 forks source link

Minimal example of fastify + apollo graphql server + fastify websocket grapqhl subscriptions #291

Open kelvin2200 opened 6 months ago

kelvin2200 commented 6 months ago

Prerequisites

🚀 Feature Proposal

Provide a minimal example for usage of this plugin with @apollo/server v4 and implementing graphql subscriptions.

Motivation

Couldn't find a practical example other than https://www.apollographql.com/docs/apollo-server/data/subscriptions/ to specifically deal with this plugin and fastify

Example

import { ApolloServer } from '@apollo/server';
import { ApolloServerPluginLandingPageLocalDefault } from '@apollo/server/plugin/landingPage/default';
import fastifyApollo, { fastifyApolloDrainPlugin } from '@as-integrations/fastify';

import Cors from '@fastify/cors';
import { env } from '@lib/env';

import fastifyCookie from '@fastify/cookie';

import { Context } from '@typings/context';

import Fastify from 'fastify';

import { apolloCtxRegisterFn } from 'middleware/apollo-ctx';
import { errorHandler } from 'middleware/error-handler';
import { ctxRequestDecorator } from 'middleware/global-ctx';
import fastifyWebsocket from "@fastify/websocket";

const fastify = Fastify();

await fastify.register(fastifyWebsocket);

const apollo = new ApolloServer<Context>({
    schema: schema, // obtained from somewhere
    plugins: [
        fastifyApolloDrainPlugin(fastify),
        ApolloServerPluginLandingPageLocalDefault({
            includeCookies: true,
        }),
    ],
});

fastify.setErrorHandler(errorHandler);

await apollo.start();

await fastify.register(Cors, {
    ...
        ...
        ...
});

await fastify.register(fastifyCookie, {});
await fastify.register(ctxRequestDecorator);

// the ws server should technically listen to the same `/graphql` route
// can't figure out what the next step is here
// do I register the ws separately and bind it to GET requests on `/graphql`?
// can I register it along with the apollo graphql handler?
await fastify.register(fastifyApollo(apollo), apolloCtxRegisterFn);

await fastify.listen({
    port: env.SERVER_PORT,
});

console.log(`🚀 Server ready at http://localhost:${env.SERVER_PORT}/graphql`);