|
| 1 | +import { execSync } from 'node:child_process' |
| 2 | + |
| 3 | +import { Client } from 'discord.js' |
| 4 | + |
| 5 | +import { env } from '@/env' |
| 6 | +import { prisma } from '@/lib/prisma' |
| 7 | + |
| 8 | +import { logger } from './logger' |
| 9 | + |
| 10 | +async function createDatabase(client: Client<true>) { |
| 11 | + const guild = client.guilds.cache.get(env.DISCORD_GUILD_ID) |
| 12 | + if (!guild) { |
| 13 | + logger.error( |
| 14 | + `Guild with ID ${env.DISCORD_GUILD_ID} not found in cache.`, |
| 15 | + ) |
| 16 | + return |
| 17 | + } |
| 18 | + |
| 19 | + logger.log(`⚙️ Creating database for guild ${guild.name}`) |
| 20 | + try { |
| 21 | + await prisma.discordGuild.upsert({ |
| 22 | + where: { id: guild.id }, |
| 23 | + update: { |
| 24 | + name: guild.name, |
| 25 | + icon: guild.iconURL() ?? undefined, |
| 26 | + }, |
| 27 | + |
| 28 | + create: { |
| 29 | + id: guild.id, |
| 30 | + name: guild.name, |
| 31 | + icon: guild.iconURL() ?? undefined, |
| 32 | + env: { |
| 33 | + create: { |
| 34 | + initialMoneyValue: 301.0, |
| 35 | + }, |
| 36 | + }, |
| 37 | + }, |
| 38 | + }) |
| 39 | + |
| 40 | + logger.success(`Guild successfully synced: ${guild.name}`) |
| 41 | + } catch (err) { |
| 42 | + logger.error(`Failed to sync guild ${guild.name}:`, err) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +function applyMigrations() { |
| 47 | + try { |
| 48 | + execSync('npx prisma migrate deploy', { stdio: 'inherit' }) |
| 49 | + logger.success('Migrations applied successfully.') |
| 50 | + } catch (err) { |
| 51 | + logger.error('Error while applying migrations:', err) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +export async function setupDatabase(client: Client<true>) { |
| 56 | + const guildId = env.DISCORD_GUILD_ID |
| 57 | + |
| 58 | + const exists = await prisma.discordGuild.findUnique({ |
| 59 | + where: { id: guildId }, |
| 60 | + }) |
| 61 | + |
| 62 | + if (exists) { |
| 63 | + logger.log('Guild already registered. Applying migrations...') |
| 64 | + applyMigrations() |
| 65 | + return |
| 66 | + } |
| 67 | + |
| 68 | + logger.log('Guild not found in the database. Creating structure...') |
| 69 | + await createDatabase(client) |
| 70 | +} |
0 commit comments