113 lines
2.6 KiB
TypeScript
113 lines
2.6 KiB
TypeScript
#!/usr/bin/env tsx
|
|
|
|
/**
|
|
* Database seeding script
|
|
* Creates sample data for development and testing
|
|
*/
|
|
|
|
import { connectDB } from '../lib/mongodb'
|
|
import { User } from '../models/user'
|
|
import bcrypt from 'bcryptjs'
|
|
import mongoose from 'mongoose'
|
|
|
|
interface SeedUser {
|
|
name: string
|
|
email: string
|
|
password: string
|
|
}
|
|
|
|
const sampleUsers: SeedUser[] = [
|
|
{
|
|
name: 'Admin User',
|
|
email: 'admin@siliconpin.com',
|
|
password: 'admin123',
|
|
},
|
|
{
|
|
name: 'John Doe',
|
|
email: 'john@example.com',
|
|
password: 'password123',
|
|
},
|
|
{
|
|
name: 'Jane Smith',
|
|
email: 'jane@example.com',
|
|
password: 'password123',
|
|
},
|
|
{
|
|
name: 'Bob Johnson',
|
|
email: 'bob@example.com',
|
|
password: 'password123',
|
|
},
|
|
]
|
|
|
|
async function seedUsers() {
|
|
console.log('🌱 Seeding users...')
|
|
|
|
for (const userData of sampleUsers) {
|
|
// Check if user already exists
|
|
const existingUser = await User.findOne({ email: userData.email })
|
|
if (existingUser) {
|
|
console.log(` ⏭️ User ${userData.email} already exists, skipping`)
|
|
continue
|
|
}
|
|
|
|
// Create user with admin role for first user (password will be hashed by pre-save hook)
|
|
const user = new User({
|
|
name: userData.name,
|
|
email: userData.email,
|
|
password: userData.password,
|
|
role: userData.email === 'admin@siliconpin.com' ? 'admin' : 'user',
|
|
siliconId: `SP${Math.random().toString(36).substr(2, 8).toUpperCase()}`,
|
|
isVerified: true,
|
|
balance: userData.email === 'admin@siliconpin.com' ? 100000 : 5000,
|
|
})
|
|
|
|
await user.save()
|
|
console.log(` ✅ Created user: ${userData.email}`)
|
|
}
|
|
}
|
|
|
|
async function main() {
|
|
try {
|
|
console.log('🚀 Starting database seed...')
|
|
|
|
// Connect to database
|
|
await connectDB()
|
|
console.log('📦 Connected to MongoDB')
|
|
|
|
// Seed data
|
|
await seedUsers()
|
|
|
|
console.log('🎉 Database seeding completed successfully!')
|
|
console.log('\n📝 Sample credentials for testing:')
|
|
sampleUsers.forEach((user) => {
|
|
console.log(` Email: ${user.email} | Password: ${user.password}`)
|
|
})
|
|
} catch (error) {
|
|
console.error('❌ Error seeding database:', error)
|
|
process.exit(1)
|
|
} finally {
|
|
// 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 seeder
|
|
if (require.main === module) {
|
|
main()
|
|
}
|
|
|
|
export { main as seedDatabase }
|