ai-wpa/scripts/reset-db.ts

105 lines
2.7 KiB
TypeScript
Raw Permalink Blame History

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

#!/usr/bin/env tsx
/**
* Database reset script
* Clears all collections and optionally reseeds data
*/
import { connectDB } from '../lib/mongodb'
import { User } from '../models/user'
import mongoose from 'mongoose'
import { seedDatabase } from './seed'
import readline from 'readline'
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
function askQuestion(question: string): Promise<string> {
return new Promise((resolve) => {
rl.question(question, (answer) => {
resolve(answer.trim().toLowerCase())
})
})
}
async function clearCollections() {
console.log('🧹 Clearing collections...')
// Get all collections
const collections = await mongoose.connection.db.collections()
for (const collection of collections) {
const count = await collection.countDocuments()
if (count > 0) {
await collection.deleteMany({})
console.log(` ✅ Cleared ${collection.collectionName}: ${count} documents removed`)
} else {
console.log(` ⏭️ ${collection.collectionName}: already empty`)
}
}
}
async function main() {
try {
console.log('🔄 Database Reset Tool')
console.log('=====================')
// Connect to database
await connectDB()
console.log('📦 Connected to MongoDB')
// Get current database name
const dbName = mongoose.connection.db.databaseName
console.log(`🗄️ Database: ${dbName}`)
// Confirm reset
console.log('\n⚠ This will permanently delete ALL data in the database!')
const confirmed = await askQuestion('Are you sure you want to continue? (yes/no): ')
if (confirmed !== 'yes' && confirmed !== 'y') {
console.log('❌ Reset cancelled')
return
}
// Clear all collections
await clearCollections()
// Ask if user wants to reseed
const reseed = await askQuestion('\n🌱 Do you want to seed sample data? (yes/no): ')
if (reseed === 'yes' || reseed === 'y') {
console.log('\n🌱 Reseeding database...')
await seedDatabase()
}
console.log('\n🎉 Database reset completed successfully!')
} catch (error) {
console.error('❌ Error resetting database:', error)
process.exit(1)
} finally {
rl.close()
// Close database connection
await mongoose.connection.close()
console.log('🔌 Database connection closed')
process.exit(0)
}
}
// Handle uncaught errors
process.on('unhandledRejection', (error) => {
console.error('❌ Unhandled rejection:', error)
process.exit(1)
})
process.on('uncaughtException', (error) => {
console.error('❌ Uncaught exception:', error)
process.exit(1)
})
// Run the reset tool
if (require.main === module) {
main()
}