import { Args, Context, Mutation, Parent, ResolveField, Resolver, Subscription, } from '@nestjs/graphql'; import { Entry } from './models/entry.model'; import { PrismaService } from '../prisma/prisma.service'; import { GraphQLString } from 'graphql'; import { BadRequestException, NotFoundException, UseGuards, } from '@nestjs/common'; import { Request } from 'express'; import { GraphQLAuthGuard } from 'src/auth/graphql-auth.guard'; import { pubSub } from 'src/pubSub.instance'; @Resolver(() => Entry) //@UseGuards(GraphQLAuthGuard) export class EntryResolver { constructor(private prismaService: PrismaService) {} @ResolveField('agent') async agent(@Parent() entry: Entry) { const result = await this.prismaService.entry.findFirst({ where: { id: entry.id }, select: { agent: true }, }); return result.agent; } @Subscription(() => Entry) newEntry(){ return pubSub.asyncIterator('newEntry'); } @Mutation(() => Entry) async unlockEntry( @Args({ name: 'id', type: () => GraphQLString }) id: string, @Context() { req }: { req: Request }, ) { const unlock = await this.prismaService.entry.findFirst({ where: { id, private: true, }, }); if (!unlock) throw new NotFoundException(); if (req.group.tokens <= 0) throw new BadRequestException('No remaining tokens'); const count = await this.prismaService.group.count({ where: { unlocks: { some: { id }, }, }, }); if (count > 0) throw new BadRequestException('Already unlocked'); await this.prismaService.group.update({ where: { id: req.group.id }, data: { tokens: req.group.tokens - 1, unlocks: { connect: { id }, }, }, }); return { ...unlock, locked: false, }; } }