fastify-websocket icon indicating copy to clipboard operation
fastify-websocket copied to clipboard

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

Open kelvin2200 opened this issue 1 year ago • 1 comments
trafficstars

Prerequisites

  • [X] I have written a descriptive issue title
  • [X] I have searched existing issues to ensure the feature has not already been requested

🚀 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`);

kelvin2200 avatar Mar 08 '24 11:03 kelvin2200