-
Daniel Gerdes authoredDaniel Gerdes authored
entry.resolver.ts 2.22 KiB
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 { GroupAuthGuard } from '../auth/group-auth.guard';
import { pubSub } from '../pubSub.instance';
@Resolver(() => Entry)
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');
}
@UseGuards(GroupAuthGuard)
@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: {
id: req.group.id,
unlocks: {
some: { id },
},
},
});
if (count > 0) throw new BadRequestException('Already unlocked');
const group = await this.prismaService.group.update({
where: { id: req.group.id },
data: {
tokens: req.group.tokens - 1,
unlocks: {
connect: { id },
},
},
});
await pubSub.publish('updateToken', {
updateToken: group,
});
return {
...unlock,
locked: false,
};
}
}