Created
September 20, 2021 23:50
-
-
Save cgodkin/ad9379db95d68464f4b203598bbb8030 to your computer and use it in GitHub Desktop.
Using subscriptions with generated CRUD resolvers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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, | |
}; | |
}, | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This worked perfect.