How to use the @nestjs/graphql.Subscription function in @nestjs/graphql

To help you get started, we’ve selected a few @nestjs/graphql examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github neoteric-eu / nestjs-auth / src / app / user / user.resolver.ts View on Github external
@Mutation('deleteUser')
	async delete(@Args('deleteUserInput') args: DeleteUserDto): Promise {
		const deletedUser = await this.userService.delete(args.id);
		await this.pubSub.publish('userDeleted', {userDeleted: deletedUser});
		return deletedUser;
	}

	@Mutation('updateUser')
	async update(@CurrentUser() user: UserEntity, @Args('updateUserInput') args: UpdateUserDto): Promise {
		const updatedUser = await this.userService.patch(user.id.toString(), args);
		await this.pubSub.publish('userUpdated', {userUpdated: updatedUser});
		return updatedUser;
	}

	@Subscription('userCreated')
	userCreated() {
		return {
			subscribe: () => this.pubSub.asyncIterator('userCreated')
		};
	}

	@Subscription('userDeleted')
	userDeleted() {
		return {
			subscribe: () => this.pubSub.asyncIterator('userDeleted')
		};
	}

	@ResolveProperty('subscriptions')
	getHome(@Parent() user: UserEntity): Promise {
		return this.userService.subscription.findOne({where: {user: {eq: user.id.toString()}}});
github nelsonBlack / nestjs-mysql-graphql-sequelize-typescript / src / cats / cats.resolvers.ts View on Github external
@Subscription('catCreated')
  catCreated() {
    return {
      subscribe: () => pubsub.asyncIterator('catCreated'),
    };
  }

  @Subscription('catUpdated')
  catUpdated() {
    return {
      subscribe: () => pubsub.asyncIterator('catUpdated'),
    };
  }

  @Subscription('catDeleted')
  catDeleted() {
    return {
      subscribe: () => pubsub.asyncIterator('catDeleted'),
    };
  }
}
github jimmyleray / Emendare / server / src / resolvers / event / event.resolver.ts View on Github external
@Query(returns => EventsResponse)
  async events(
    @Args('data') data: EventsInputs
  ): Promise> {
    return this.eventService.getEventsByGroup(data.limit, data.lastEventDate)
  }

  @Subscription(returns => EventResponse, {
    nullable: true,
    resolve: payload => payload
  })
  newEvent() {
    return pubSub.asyncIterator(Topic.NewEvent)
  }

  @Subscription(returns => EventResponse, {
    nullable: true,
    resolve: payload => payload
  })
  deleteEvent() {
    return pubSub.asyncIterator(Topic.DeleteEvent)
  }
}
github MarcinMiler / tinder-clone / packages / server / src / modules / match / match.resolver.ts View on Github external
import { MemberService } from '../member/member.service'

@Resolver('Match')
export class MatchResolver {
    constructor(
        @Inject('PubSub') private readonly pubSub: PubSub,
        private readonly matchService: MatchService,
        private readonly memberService: MemberService
    ) {}

    @Query('matches')
    matches(@Args('userId') userId: number) {
        return this.matchService.findByUserId(userId)
    }

    @Subscription('newMatch')
    createdMessage() {
        return {
            resolve: async (payload, args) => {
                if (
                    payload.userId1 !== args.userId &&
                    payload.userId2 !== args.userId
                ) {
                    return null
                }

                return await this.memberService.findByMatchId(
                    payload.id,
                    args.userId,
                    ['matchedUser']
                )
            },
github penta-jelly / re-radio / server / src / radio / user / resolvers / user-subscription.resolver.ts View on Github external
import { Args, Resolver, Subscription } from '@nestjs/graphql';
import { PubSub } from 'core/pub-sub/pub-sub.service';
import { EntitySubscription } from 'core/typeorm/entity-subscription.interface';
import { StationSubscriptionDTO } from 'radio/station/dto/station-subscription.dto';
import { UserSubscriptionDTO } from '../dto/user-subscription.dto';
import { User } from '../entities/user.entity';
import { UserFindOneWhereInput } from '../user.input';
import { USER_SUBSCRIPTION } from '../user.subscriber';

@Resolver(of => StationSubscriptionDTO)
export class UserSubscriptionResolver {
  constructor(private readonly pubSub: PubSub) {}

  @Subscription(returns => UserSubscriptionDTO, { name: 'user' })
  async *userSubscription(@Args({ name: 'where', type: () => UserFindOneWhereInput }) where: UserFindOneWhereInput) {
    for await (const payload of this.pubSub.asyncIterable>(USER_SUBSCRIPTION)) {
      if (!Object.keys(where).every(key => where[key] === payload.entity[key])) {
        continue;
      }
      yield { user: payload };
    }
  }
}
github neoteric-eu / nestjs-auth / src / app / home-media / home-media.resolver.ts View on Github external
const updatedHomeMedia = await this.homeMediaService.update(args);
		await this.pubSub.publish('homeMediaUpdated', {homeMediaCreated: updatedHomeMedia});
		return updatedHomeMedia;
	}

	@Mutation('deleteHomeMedia')
	async delete(@CurrentUser() user: User, @Args('deleteHomeMediaInput') args: DeleteHomeMediaInput): Promise {
		const deletedHomeMedia = await this.homeMediaService.delete(args.id);
		await this.pubSub.publish('homeMediaDeleted', {homeMediaDeleted: deletedHomeMedia});
		this.client.send({cmd: MEDIA_CMD_DELETE}, deletedHomeMedia).subscribe(() => {}, error => {
			this.logger.error(error, '');
		});
		return deletedHomeMedia;
	}

	@Subscription('homeMediaCreated')
	homeMediaCreated() {
		return {
			subscribe: () => this.pubSub.asyncIterator('homeMediaCreated')
		};
	}

	@Subscription('homeMediaUpdated')
	homeMediaUpdated() {
		return {
			subscribe: () => this.pubSub.asyncIterator('homeMediaUpdated')
		};
	}

	@Subscription('homeMediaDeleted')
	homeMediaDeleted() {
		return {
github scalio / bazel-nx-example / apps / api / src / cats / cats.resolvers.ts View on Github external
id: number,
  ): Promise {
    this.logger.log('getCat called');
    return await this.catsService.findOneById(id);
  }

  @Mutation('createCat')
  @UseGuards(GqlAuthGuard)
  async create(@Args('createCatInput') args: CreateCatDto): Promise {
    this.logger.log('createCat called');
    const createdCat = await this.catsService.create(args);
    pubSub.publish('catCreated', { catCreated: createdCat });
    return createdCat;
  }

  @Subscription('catCreated')
  catCreated() {
    return pubSub.asyncIterator('catCreated');
  }
}
github chnirt / nestjs-graphql-best-practice / src / resolvers / order / order.resolver.ts View on Github external
return true
		} catch (error) {
			throw new ApolloError(error)
		}
	}

	@Mutation(() => Boolean)
	async deleteOrder(@Args('id') id: string): Promise {
		try {
			return (await this.orderRepository.deleteOne({ _id: id })) ? true : false
		} catch (error) {
			throw new ApolloError(error)
		}
	}

	@Subscription()
	async ordersByMenuCreated(@Context('pubSub') pubSub: any) {
		return pubSub.asyncIterator('ordersByMenuCreated')
	}
}
github penta-jelly / re-radio / server / src / radio / station-tags / station-tags.resolver.ts View on Github external
@Mutation('deleteStationTag')
  @UseGuards(AuthenticationGuard, AuthorizationGuard)
  @Roles(['ADMIN'])
  async deleteStationTag(@Args() args, @Info() info): Promise {
    return await this.prisma.mutation.deleteStationTag(args, info);
  }

  @Mutation('deleteManyStationTags')
  @UseGuards(AuthenticationGuard, AuthorizationGuard)
  @Roles(['ADMIN'])
  async deleteManyStationTags(@Args() args, @Info() info): Promise {
    return await this.prisma.mutation.deleteManyStationTags(args, info);
  }

  @Subscription('stationTag')
  onStationMutation(@Args() args, @Info() info) {
    return this.prisma.subscription.stationTag(args, info);
  }
}
github neoteric-eu / nestjs-auth / src / app / message / resolvers / message.resolver.ts View on Github external
return {
			subscribe: withFilter(() => this.pubSub.asyncIterator('messageDeleted'),
				(payload, variables, context) => this.subscriptionsService.messageDeleted(payload, variables, context))
		};
	}

	@ResolveProperty('author')
	async getAuthor(@Parent() message: MessageEntity): Promise {
		try {
			return this.userService.findOneById(message.authorId);
		} catch (e) {
			return this.userService.create({});
		}
	}

	@Subscription('newMessage')
	newMessage() {
		return {
			subscribe: withFilter(() => this.pubSub.asyncIterator('newMessage'),
				(payload, variables, context) => this.subscriptionsService.newMessage(payload, variables, context))
		};
	}

	@Subscription('startTyping')
	onStartTyping() {
		return {
			subscribe: withFilter(() => this.pubSub.asyncIterator('startTyping'),
				(payload, variables, context) => this.subscriptionsService.startTyping(payload, variables, context))
		};
	}

	@Subscription('stopTyping')