-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.ts
153 lines (138 loc) · 2.62 KB
/
db.ts
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import { PrismaClient, type Item } from '@prisma/client'
const db = new PrismaClient()
export default db
export async function getTeamForUser(userId: number) {
return db.team.findFirstOrThrow({
where: {
users: {
some: {
id: userId
}
}
}
})
}
export async function getQuestForUser(userId: number) {
return await db.quest.findFirst({
where: {
userId: userId
},
select: {
id: true,
task: true,
type: true,
answer: true,
reward: true
}
})
}
export async function getItemsForUser(userId: number) {
return (
await db.transaction.findMany({
where: {
userId: userId,
NOT: {
itemId: null
}
},
select: {
item: true
}
})
).map((transaction) => transaction.item)
}
export async function getAdsForUser(userId: number) {
const tags = await db.tag.findMany({
where: {
users: {
some: {
id: userId
}
},
ads: {
every: {
viewRemaining: {
gt: 0
}
}
}
},
include: {
ads: true
}
})
return tags.map((tag) => tag.ads).flat()
}
// eslint-disable-next-line @typescript-eslint/ban-types
export async function buy(userId: number, cost: number, item: Item | String) {
const team = await getTeamForUser(userId)
if (!team) {
throw new Error('No team')
}
if (team.money < cost) {
throw new Error('Team has not enough money')
}
await db.team.update({
where: {
id: team.id
},
data: {
money: {
decrement: cost
}
}
})
const data = {
amount: cost,
userId: userId,
teamId: team.id
}
if (item instanceof String) {
//@ts-expect-error add description to data if item is a string
data.description = item.toString()
} else {
//@ts-expect-error add itemId to data if item is an Item
data.itemId = item.id
}
return db.transaction.create({
data
})
}
export async function userHasTag(userId: number, tagName: string) {
const tag = await db.tag.findFirst({
where: {
name: tagName,
users: {
some: {
id: userId
}
}
}
})
return tag != null
}
export async function buyAddTag(
userId: number,
cost: number,
description: string,
tag: string
) {
await buy(userId, cost, new String(description))
const id = await db.tag.findFirstOrThrow({
where: {
name: tag
}
})
await db.user.update({
where: {
id: userId
},
data: {
tags: {
connect: {
id: id!.id
}
}
}
})
}