Skip to content

Instantly share code, notes, and snippets.

@VeeeneX
Created October 17, 2021 10:58
Show Gist options
  • Save VeeeneX/7f5581454fda17009750c1d63ccc569f to your computer and use it in GitHub Desktop.
Save VeeeneX/7f5581454fda17009750c1d63ccc569f to your computer and use it in GitHub Desktop.
GraphQL Subscription problem
import { ObjectType, Field } from '@nestjs/graphql';
import { Link } from './link.object-type';
import { Node } from './node.object-type';
@ObjectType()
export class NetworkChange {
@Field(() => String, { defaultValue: '', nullable: true })
test: string;
}
import {
Resolver,
Query,
Args,
Mutation,
ID,
Subscription,
} from '@nestjs/graphql';
import { Link } from './object-types/link.object-type';
import { CreateLinkInput } from './dto/create-link.input';
import { CaseService } from '../workspace/services/case.service';
import { Inject } from '@nestjs/common';
import { PUB_SUB } from '@infrastructure/providers/pub-sub.provider';
import { NetworkChange } from './object-types/network-change.object-type';
import { RedisPubSub } from 'graphql-redis-subscriptions';
const LINK_ADDED = 'linkAdded';
@Resolver(() => Network)
export class NetworkResolver {
constructor(
@Inject(PUB_SUB) private readonly pubSub: RedisPubSub,
) {}
@Mutation(() => Link)
createLink(@Args('createLinkInput') createLinkInput: CreateLinkInput) {
this.pubSub.publish('networkChanged', {
test: '',
});
return this.networkService.createLink(createLinkInput);
}
@Subscription(() => NetworkChange, {
resolve: (p) => {
return p
}
})
networkChanged() {
return this.pubSub.asyncIterator('networkChanged');
}
}
import { RedisPubSub } from 'graphql-redis-subscriptions';
import Redis from 'ioredis';
export const PUB_SUB = 'PUB_SUB';
export const pubSubProvider = {
provide: PUB_SUB,
useFactory: () => {
const options = {
host: 'localhost',
port: 6379,
retryStrategy: (times) => Math.min(times * 50, 2000),
};
return new RedisPubSub({
publisher: new Redis(options),
subscriber: new Redis(options),
});
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment