Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
2 tasks done
kelvin2200 opened this issue Mar 8, 2024 · 0 comments

Comments

@kelvin2200
Copy link

kelvin2200 commented Mar 8, 2024

Prerequisites

  • I have written a descriptive issue title
  • 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`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant