Newer
Older
Args,
Context,
Mutation,
Parent,
Query,
ResolveField,
Resolver,
Subscription,
InternalServerErrorException,
NotFoundException,
UseGuards,
import { Request } from 'express';
import { EntryService } from '../utils/entry.service';
import { AgentModel } from './models/agent.model';
import { GroupGuard } from '../auth/group.guard';
import { PubSub } from 'graphql-subscriptions';
import { Entry, Group } from '@prisma/client';
private readonly pubSub: PubSub,
private readonly prisma: PrismaService,
private readonly entryService: EntryService,
) {}
@Subscription(() => EntryModel, {
filter: (
payload: { onEntryUpdate: Entry & { by?: Group } },
variables,
{ req },
) => {
if (req.group && payload.onEntryUpdate.by)
return req.group.id === payload.onEntryUpdate.by.id;
@UseGuards(AuthGuard)
onEntryUpdate() {
return this.pubSub.asyncIterator('onEntryUpdate');
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
}
@Mutation(() => EntryModel)
@UseGuards(AuthGuard, GroupGuard)
unlockEntry(
@Args('id') id: string,
@Context() { req }: { req: Request },
): Promise<EntryModel> {
return this.prisma.$transaction(async (prisma) => {
const entry = await prisma.entry.findFirst({
where: {
id,
unlockedBy: {
none: { id: req.group.id },
},
},
});
if (!entry) throw new NotFoundException();
if (req.group.tokens < entry.cost)
throw new BadRequestException('Not enough tokens');
const group = await prisma.group.update({
where: { id: req.group.id },
data: {
tokens: { decrement: entry.cost },
unlocks: {
connect: { id: entry.id },
},
},
});
if (!group)
throw new InternalServerErrorException('Group not found');
await this.pubSub.publish('onEntryUpdate', {
await this.pubSub.publish('onGroupUpdate', {
onGroupUpdate: group,
});
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
return this.entryService.unlockedEntry(entry);
});
}
@Query(() => [EntryModel])
@UseGuards(AuthGuard)
async getEntries(@Context() { req }: { req: Request }) {
if (req.agent)
return this.prisma.entry
.findMany()
.then((entries) =>
entries.map(this.entryService.unlockedEntry),
);
return await this.entryService.getAccessibleEntries(req.group.id);
}
@ResolveField('agent')
async agent(@Parent() parent: EntryModel): Promise<AgentModel> {
return this.prisma.agent.findFirst({
where: {
entries: {
some: { id: parent.id },
},
},
select: {
id: true,
name: true,
slug: false,
flags: true,
},
});
}