Skip to content
Snippets Groups Projects
entry.resolver.ts 1.91 KiB
Newer Older
  • Learn to ignore specific revisions
  • import { Args, Context, Mutation, Parent, ResolveField, Resolver } from '@nestjs/graphql';
    
    Pascal Kosak's avatar
    Pascal Kosak committed
    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';
    
    Pascal Kosak's avatar
    Pascal Kosak committed
    
    @Resolver(() => Entry)
    
    Pascal Kosak's avatar
    Pascal Kosak committed
    export class EntryResolver {
    
    Pascal Kosak's avatar
    Pascal Kosak committed
        constructor(private prismaService: PrismaService) {}
    
    Pascal Kosak's avatar
    Pascal Kosak committed
    
        @ResolveField('agent')
        async agent(@Parent() entry: Entry) {
            const result = await this.prismaService.entry.findFirst({
                where: { id: entry.id },
                select: { agent: true },
            });
    
            return result.agent;
        }
    
    
        @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 },
                    },
                },
            });
    
    
    Pascal Kosak's avatar
    Pascal Kosak committed
    }