Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
import { UseGuards, NotFoundException } from "@nestjs/common";
import { Args, Context, Mutation, Parent, ResolveField, Resolver, Subscription } from "@nestjs/graphql";
import { GraphQLString, GraphQLInt } from 'graphql';
import { Request } from "express";
import { GroupAuthGuard } from "../auth/graphql-auth.guard";
import { PrismaService } from "../prisma/prisma.service";
import { TokenCode } from "./models/tokenCode.model";
import { AgentAuthGuard } from "../auth/agent-auth.guard";
import { pubSub } from "../pubSub.instance";
@Resolver(() => TokenCode)
export class TokenCodeResolver {
constructor(private prismaService: PrismaService) {}
// TODO: protect subscription
@Subscription(() => TokenCode, {
filter: (payload, variables) =>
payload.newTokenCode.agent.id === variables.id,
})
newTokenCode(@Args('id') id: string){
return pubSub.asyncIterator('newTokenCode');
}
@UseGuards(AgentAuthGuard)
@Mutation(() => TokenCode)
async tokenCode(@Context() { req }: { req: Request }) {
let tokenCode = await this.prismaService.tokenCode.findFirst({
where: {
id: req.agent.tokenCodeId,
},
});
if (!tokenCode) {
tokenCode = await this.prismaService.tokenCode.create({
data: {
value: 1,
agent: {
connect: { id: req.agent.id },
},
},
});
pubSub.publish('newTokenCode', {
newTokenCode: tokenCode
});
}
return tokenCode;
}
@UseGuards(GroupAuthGuard)
@Mutation(() => GraphQLInt)
async redeemCode(
@Args({ name: 'code', type: () => GraphQLString }) code: string,
@Context() { req }: { req: Request },
) {
const tokenCode = await this.prismaService.tokenCode.findFirst({
where: { id: code },
include: {
agent: true,
}
});
if (!tokenCode)
throw new NotFoundException();
const newTokenCode = await this.prismaService.tokenCode.create({
data: {
value: 1,
agent: {
connect: { id: tokenCode.agent.id },
},
},
include: {
agent: true,
}
});
pubSub.publish('newTokenCode', {
newTokenCode: newTokenCode,
});
await this.prismaService.tokenCode.delete({
where: { id: tokenCode.id },
});
req.group = await this.prismaService.group.update({
where: { id: req.group.id },
data: {
tokens: {
increment: tokenCode.value,
},
},
});
pubSub.publish('updateToken', {
updateToken: req.group,
});
return tokenCode.value;
}
@ResolveField('agent')
agent(@Parent() token: TokenCode) {
return this.prismaService.agent.findFirst({
where: {
tokenCodeId: token.id,
},
});
}
}