-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathseed.ts
435 lines (371 loc) Β· 13.1 KB
/
seed.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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
import { createPostSlug, extractPostSlug, getPostExcerpt } from "~/helpers/post"
import { prisma } from "~/libs/db.server"
import { hashPassword } from "~/utils/encryption.server"
import { logEnv } from "~/utils/log.server"
import { createSlug } from "~/utils/string"
import dataCredentialUsers from "./credentials/users.json"
import dataEventCategories from "./data/event-categories.json"
import dataEventFormats from "./data/event-formats.json"
import dataEventMedia from "./data/event-media.json"
import dataEventStatuses from "./data/event-statuses.json"
import { dataEvents } from "./data/events"
import dataPostStatuses from "./data/post-statuses.json"
import dataPosts from "./data/posts.json"
import dataRoles from "./data/roles.json"
import dataTags from "./data/tags.json"
import dataTicketCategories from "./data/ticket-categories.json"
/**
* Enable and disable seed items by commenting them
*/
const enabledSeedItems = [
"permissions",
"tags",
"roles",
"users",
"postStatuses",
"posts",
"eventStatuses",
"events",
"eventCategories",
"eventFormats",
"eventMedia",
"ticketCategories",
]
async function main() {
logEnv()
const seeds: { [key: string]: () => Promise<any> } = {
permissions: seedPermissions,
tags: seedTags,
roles: seedRoles,
users: seedUsers,
postStatuses: seedPostStatuses,
posts: seedPosts,
eventStatuses: seedEventStatuses,
eventCategories: seedEventCategories,
eventFormats: seedEventFormats,
eventMedia: seedEventMedia,
events: seedEvents,
ticketCategories: seedTicketCategories,
}
for (const seedName of enabledSeedItems) {
const seed = seeds[seedName]
if (seed) {
await seed()
}
}
}
async function seedPermissions() {
console.info("\nπ Seed permissions")
console.info("π Count permissions", await prisma.permission.count())
console.info("π Deleted permissions", await prisma.permission.deleteMany())
console.time("π Created permissions")
const entities = ["USER", "NOTE"]
const actions = ["CREATE", "READ", "UPDATE", "DELETE"]
const accesses = ["OWN", "ANY"] as const
for (const entity of entities) {
for (const action of actions) {
for (const access of accesses) {
await prisma.permission.create({
data: { entity, action, access },
})
}
}
}
console.timeEnd("π Created permissions")
}
async function seedTags() {
console.info("\nπͺ§ Seed tags")
console.info("πͺ§ Count tags", await prisma.userTag.count())
console.info("πͺ§ Deleted tags", await prisma.userTag.deleteMany())
console.time("πͺ§ Created tags")
const userTags = await prisma.userTag.createMany({
data: dataTags,
})
console.timeEnd(`πͺ§ Created User Tags: ${userTags.count} tags`)
}
async function seedTicketCategories() {
console.info("\nπͺ§ Seed ticket categories")
console.info(
"πͺ§ Count ticket categories",
await prisma.ticketCategory.count(),
)
// console.info("πͺ§ Deleted ticket categories", await prisma.ticketCategory.deleteMany())
console.time("πͺ§ Upserted ticket categories")
for (const statusRaw of dataTicketCategories) {
const status = await prisma.ticketCategory.upsert({
where: { symbol: statusRaw.symbol },
create: statusRaw,
update: statusRaw,
})
console.info(
`πͺ§ Upserted ticket category ${status.symbol} / ${status.name}`,
)
}
console.timeEnd("πͺ§ Upserted ticket categories")
}
async function seedRoles() {
console.info("\nπ Seed roles")
console.info("π Count roles", await prisma.role.count())
// console.info("π Deleted roles", await prisma.role.deleteMany())
console.time("π Upserted roles")
for (const roleRaw of dataRoles) {
const roleData = {
symbol: roleRaw.symbol,
name: roleRaw.name,
permissions: {
connect: await prisma.permission.findMany({
select: { id: true },
where: { access: roleRaw.permissionsAccess },
}),
},
}
const role = await prisma.role.upsert({
where: { symbol: roleRaw.symbol },
create: roleData,
update: roleData,
})
console.info(`π Upserted role ${role.symbol} / ${role.name}`)
}
console.timeEnd("π Upserted roles")
}
async function seedUsers() {
console.info("\nπ€ Seed users")
console.info("π€ Count users", await prisma.user.count())
// console.info("π€ Deleted users", await prisma.user.deleteMany())
if (!Array.isArray(dataCredentialUsers)) {
console.error(`π΄ Please create prisma/credentials/users.json file`)
console.error(`π΄ Check README for the guide`)
return null
}
const userTags = await prisma.userTag.findMany()
const TEAM = userTags.find(tag => tag.symbol === "TEAM")
const ADVISOR = userTags.find(tag => tag.symbol === "ADVISOR")
const DEVELOPER = userTags.find(tag => tag.symbol === "DEVELOPER")
const SPEAKER = userTags.find(tag => tag.symbol === "SPEAKER")
const MEMBER = userTags.find(tag => tag.symbol === "MEMBER")
const UNKNOWN = userTags.find(tag => tag.symbol === "UNKNOWN")
if (!TEAM || !ADVISOR || !DEVELOPER || !SPEAKER || !MEMBER || !UNKNOWN)
return null
const dataCredentialUsersSeed = dataCredentialUsers.map(user => {
const tagsIds =
Array.isArray(user.tags) &&
user.tags.map(tag => {
if (tag === "TEAM") return { id: TEAM.id }
if (tag === "ADVISOR") return { id: ADVISOR.id }
if (tag === "DEVELOPER") return { id: DEVELOPER.id }
if (tag === "SPEAKER") return { id: SPEAKER.id }
if (tag === "MEMBER") return { id: MEMBER.id }
if (tag === "UNKNOWN") return { id: UNKNOWN.id }
return { id: UNKNOWN.id }
})
return {
...user,
tags: tagsIds ? { connect: tagsIds } : undefined,
}
})
for (const userCredential of dataCredentialUsersSeed) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { password, profile, roleSymbol, ...userRaw } = userCredential
const userData = {
...userRaw,
roles: { connect: { symbol: userCredential.roleSymbol } },
}
const existingUser = await prisma.user.findUnique({
where: { username: userData.username },
include: { password: { select: { hash: true } } },
})
const userHasPassword = Boolean(existingUser?.password?.hash)
const user = await prisma.user.upsert({
where: { username: userData.username },
update: {
...userData,
password:
userCredential.password && userHasPassword
? { update: { hash: await hashPassword(userCredential.password) } }
: undefined,
profile: profile ? { update: profile } : undefined,
},
create: {
...userData,
password: userCredential.password
? { create: { hash: await hashPassword(userCredential.password) } }
: undefined,
profile: profile ? { create: profile } : undefined,
},
})
if (!user) return null
console.info(`π€ Upserted user ${user.email} / @${user.username}`)
}
}
async function seedPostStatuses() {
console.info("\nπͺ§ Seed post statuses")
console.info("πͺ§ Count post statuses", await prisma.postStatus.count())
// console.info("πͺ§ Deleted post statuses", await prisma.postStatus.deleteMany())
console.time("πͺ§ Upserted post statuses")
for (const statusRaw of dataPostStatuses) {
const status = await prisma.postStatus.upsert({
where: { symbol: statusRaw.symbol },
create: statusRaw,
update: statusRaw,
})
console.info(`πͺ§ Upserted post status ${status.symbol} / ${status.name}`)
}
console.timeEnd("πͺ§ Upserted post statuses")
}
async function seedPosts() {
console.info("\nπ Seed posts")
console.info("π Count posts", await prisma.post.count())
console.info("π Deleted posts", await prisma.post.deleteMany())
const users = await prisma.user.findMany({
select: { id: true, username: true },
})
const posts = await prisma.post.findMany({
select: { id: true, slug: true },
})
const postStatuses = await prisma.postStatus.findMany({
select: { id: true, symbol: true },
})
for (const postRaw of dataPosts) {
const user = users.find(user => user.username === postRaw.username)
if (!user) return null
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { username, statusSymbol, ...postSanitized } = postRaw
const slug = createSlug(postRaw.title) // original-slug
const postSlug = createPostSlug(postRaw.title) // modified-slug-nanoid123
const existingPost = posts.find(post => {
return slug === extractPostSlug(post.slug)
})
const status = postStatuses.find(
status => status.symbol === postRaw.statusSymbol,
)
if (!status) return null
const postData = {
...postSanitized,
// Reuse the same post slug if it already exists
slug: existingPost?.slug || postSlug,
excerpt: getPostExcerpt(postSanitized.content),
userId: user.id,
statusId: status.id,
}
const post = await prisma.post.upsert({
where: { slug: postData.slug },
update: postData,
create: postData,
})
if (!post) return null
console.info(`π Upserted post ${post.title} / ${post.slug}`)
}
}
async function seedEventStatuses() {
console.info("\nπͺ§ Seed event statuses")
console.info("πͺ§ Count event statuses", await prisma.eventStatus.count())
// console.info("πͺ§ Deleted event statuses", await prisma.eventStatus.deleteMany())
console.time("πͺ§ Upserted event statuses")
for (const statusRaw of dataEventStatuses) {
const status = await prisma.eventStatus.upsert({
where: { symbol: statusRaw.symbol },
create: statusRaw,
update: statusRaw,
})
console.info(`πͺ§ Upserted event status ${status.symbol} / ${status.name}`)
}
console.timeEnd("πͺ§ Upserted event statuses")
}
async function seedEventCategories() {
console.info("\nπͺ§ Seed event categories")
console.info("πͺ§ Count event categories", await prisma.eventCategory.count())
// console.info("πͺ§ Deleted event categories", await prisma.eventCategory.deleteMany())
console.time("πͺ§ Upserted event categories")
for (const eventCategoryRaw of dataEventCategories) {
const eventCategory = await prisma.eventCategory.upsert({
where: { symbol: eventCategoryRaw.symbol },
create: eventCategoryRaw,
update: eventCategoryRaw,
})
console.info(
`πͺ§ Upserted event category ${eventCategory.symbol} / ${eventCategory.name}`,
)
}
console.timeEnd("πͺ§ Upserted event categories")
}
async function seedEventFormats() {
console.info("\nπͺ§ Seed event formats")
console.info("πͺ§ Count event formats", await prisma.eventFormat.count())
// console.info("πͺ§ Deleted event formats", await prisma.eventFormat.deleteMany())
console.time("πͺ§ Upserted event formats")
for (const eventFormatRaw of dataEventFormats) {
const eventFormat = await prisma.eventFormat.upsert({
where: { symbol: eventFormatRaw.symbol },
create: eventFormatRaw,
update: eventFormatRaw,
})
console.info(
`πͺ§ Upserted event format ${eventFormat.symbol} / ${eventFormat.name}`,
)
}
console.timeEnd("πͺ§ Upserted event formats")
}
async function seedEventMedia() {
console.info("\nπͺ§ Seed event media")
console.info("πͺ§ Count event media", await prisma.eventMedia.count())
// console.info("πͺ§ Deleted event media", await prisma.eventMedia.deleteMany())
console.time("πͺ§ Upserted event media")
for (const eventMediaRaw of dataEventMedia) {
const eventMedia = await prisma.eventMedia.upsert({
where: { symbol: eventMediaRaw.symbol },
create: eventMediaRaw,
update: eventMediaRaw,
})
console.info(
`πͺ§ Upserted event media ${eventMedia.symbol} / ${eventMedia.name}`,
)
}
console.timeEnd("πͺ§ Upserted event media")
}
async function seedEvents() {
console.info("\nπ Seed events")
console.info("π Count events", await prisma.event.count())
// console.info("π Deleted events", await prisma.event.deleteMany())
const organizer = await prisma.user.findUnique({
where: { username: "bandungdev" },
})
if (!organizer) return null
const organizerId = organizer.id
const eventStatuses = await prisma.eventStatus.findMany({
select: { id: true, symbol: true },
})
for (const eventRaw of dataEvents) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { statusSymbol, ...eventSanitized } = eventRaw
const status = eventStatuses.find(
status => status.symbol === eventRaw.statusSymbol,
)
if (!status) return null
const event = await prisma.event.upsert({
where: { slug: eventRaw.slug },
update: {
...eventSanitized,
statusId: status.id,
organizerId,
},
create: {
...eventSanitized,
statusId: status.id,
organizerId,
},
})
if (!event) return null
console.info(`π Upserted event ${event.title} / ${event.slug}`)
}
}
main()
.then(async () => {
console.info("\nπ Seeding complete")
await prisma.$disconnect()
})
.catch(e => {
console.error(e)
console.error("\nβ Seeding failed")
prisma.$disconnect()
process.exit(1)
})