Skip to content

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

Open
@kelvin2200

Description

@kelvin2200

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions