Skip to content

Instantly share code, notes, and snippets.

@cgodkin
Created September 20, 2021 23:50
Show Gist options
  • Save cgodkin/ad9379db95d68464f4b203598bbb8030 to your computer and use it in GitHub Desktop.
Save cgodkin/ad9379db95d68464f4b203598bbb8030 to your computer and use it in GitHub Desktop.
Using subscriptions with generated CRUD resolvers
import { Field, MiddlewareFn, ObjectType, Resolver, Root, Subscription } from 'type-graphql';
import { PubSub } from 'graphql-subscriptions';
export const pubSub = new PubSub();
@ObjectType()
export class Notification {
@Field((type) => String)
query: string;
@Field((type) => Date)
date: Date;
}
interface NotificationPayload {
query: string;
}
@Resolver()
export class SubscriptionResolver {
@Subscription({
topics: 'MUTATION',
})
mutationNotification(@Root() notificationPayload: NotificationPayload): Notification {
return {
...notificationPayload,
date: new Date(),
};
}
}
export const PublishNotification: MiddlewareFn = async ({ info }, next) => {
// Perform operation.
const result = await next();
// If operation fails, we won't get here. If it succeeds, publish.
if (info.parentType.name === 'Mutation') {
const payload: NotificationPayload = { query: info.fieldName };
pubSub.publish('MUTATION', payload);
}
return result;
};
// Here's how we set up the server:
import fastify, { FastifyInstance, FastifyReply, FastifyRequest, FastifyServerOptions } from 'fastify';
import mercurius from 'mercurius';
import prismaPlugin from './plugins/prisma';
import * as tq from 'type-graphql';
import { resolvers } from '@generated/type-graphql';
import { SubscriptionResolver, PublishNotification, pubSub } from './Notification';
export function createServer(opts: FastifyServerOptions = {}): FastifyInstance {
const server = fastify(opts);
server.register(prismaPlugin);
server.register(mercurius, {
schema: tq.buildSchemaSync({
resolvers: [
...resolvers,
<other resolvers>,
SubscriptionResolver,
],
globalMiddlewares: [PublishNotification],
pubSub: pubSub,
}),
subscription: true,
path: '/graphql',
graphiql: false,
context: (request: FastifyRequest, reply: FastifyReply): Context => {
return {
prisma: server.prisma,
request,
reply,
};
},
});
@alacret
Copy link

alacret commented Oct 29, 2022

This worked perfect.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment