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: Entry & { by?: Group }, variables, { req }) => {
if (payload.by) return req.group.id === payload.by.id;
return true;
},
})
@UseGuards(AuthGuard)
onEntryUpdate() {
return this.pubSub.asyncIterator('onEntryUpdate');
47
48
49
50
51
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
}
@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', {
...entry,
by: group,
});
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,
},
});
}