-
Notifications
You must be signed in to change notification settings - Fork 27
/
json-to-prisma.ts
111 lines (82 loc) · 2.51 KB
/
json-to-prisma.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
// Migration players from JSON to Prisma
// Usage : npx dotenv-flow -- npx ts-node 9armbot-2.0/scripts/json-to-prisma.ts path/to/players.json
import { Db } from '../services/db'
import fs from 'fs'
const db = new Db()
const [, , filepath] = process.argv
interface PlayerV1_1 {
version: string
username: string
level: number
coins: number
status: string
exp: number
rollCounter: number
role: string
}
async function main() {
const dataJson = fs.readFileSync(filepath, 'utf-8')
const players = JSON.parse(dataJson) as PlayerV1_1[]
console.log('[JSON] Players count:', players.length)
const count = players.length
const playersWithUpperCasedName: PlayerV1_1[] = []
async function migrate(
player: PlayerV1_1,
idx: number,
mergeCoins: Boolean = false,
) {
const counter = `${idx + 1}/${count} : ${player.username}`
console.log('Start', counter)
if (!mergeCoins && !!player.username.match(/[A-Z]/)) {
console.log('Found player with uppercased name! Process them later...')
playersWithUpperCasedName.push(player)
return
}
const upsertedPlayer = await db.createPlayer(player.username)
console.log('Created', counter)
const playerData = {
status: player.status,
coins: player.coins,
roll_counter: player.rollCounter,
}
if (mergeCoins) {
playerData.coins += upsertedPlayer.coins
}
await db.updatePlayer(player.username, playerData)
console.log('Updated', counter)
const prismaPlayerForRecheck = await db.getPlayerbyUsername(player.username)
if (
!prismaPlayerForRecheck ||
prismaPlayerForRecheck.username != player.username.toLowerCase() ||
prismaPlayerForRecheck.status != player.status ||
prismaPlayerForRecheck.coins != playerData.coins ||
prismaPlayerForRecheck.roll_counter != player.rollCounter
) {
console.log('Player data mismatched!', {
prismaPlayerForRecheck,
player,
playerData,
})
process.exit(1)
}
console.log('Verified', counter)
return
}
// Run sequentially
await players.reduce(
(p, player, idx) => p.then(() => migrate(player, idx, false)),
Promise.resolve(),
)
console.log(
'Processing players with uppercased names : ',
playersWithUpperCasedName.length,
)
await playersWithUpperCasedName.reduce(
(p, player, idx) => p.then(() => migrate(player, idx, true)),
Promise.resolve(),
)
console.log('Migration complete!')
await db.disconnect()
process.exit(0)
}
main()