Files
drone-detector/server/models/index.js
2025-09-16 06:32:03 +02:00

91 lines
2.8 KiB
JavaScript

const { Sequelize } = require('sequelize');
// Only load .env in non-test environments
if (process.env.NODE_ENV !== 'test') {
require('dotenv').config();
}
// Configure database based on environment
let sequelize;
if (process.env.NODE_ENV === 'test') {
// Use SQLite file database for testing to allow sharing between modules
sequelize = new Sequelize({
dialect: 'sqlite',
storage: './test.db',
logging: false
});
} else {
// Use PostgreSQL for production/development
sequelize = new Sequelize(
process.env.DB_NAME || 'drone_detection',
process.env.DB_USER || 'postgres',
process.env.DB_PASSWORD || 'password',
{
host: process.env.DB_HOST || 'localhost',
port: process.env.DB_PORT || 5432,
dialect: 'postgres',
logging: process.env.NODE_ENV === 'development' ? console.log : false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
}
);
}
// Import models
const Device = require('./Device')(sequelize);
const DroneDetection = require('./DroneDetection')(sequelize);
const Heartbeat = require('./Heartbeat')(sequelize);
const User = require('./User')(sequelize);
const AlertRule = require('./AlertRule')(sequelize);
const AlertLog = require('./AlertLog')(sequelize);
const Tenant = require('./Tenant')(sequelize);
const ManagementUser = require('./ManagementUser')(sequelize);
// Define associations
Device.hasMany(DroneDetection, { foreignKey: 'device_id', as: 'detections' });
DroneDetection.belongsTo(Device, { foreignKey: 'device_id', as: 'device' });
Device.hasMany(Heartbeat, { foreignKey: 'device_id', as: 'heartbeats' });
Heartbeat.belongsTo(Device, { foreignKey: 'device_id', as: 'device' });
User.hasMany(AlertRule, { foreignKey: 'user_id', as: 'alertRules' });
AlertRule.belongsTo(User, { foreignKey: 'user_id', as: 'user' });
AlertRule.hasMany(AlertLog, { foreignKey: 'alert_rule_id', as: 'logs' });
AlertLog.belongsTo(AlertRule, { foreignKey: 'alert_rule_id', as: 'rule' });
DroneDetection.hasMany(AlertLog, { foreignKey: 'detection_id', as: 'alerts' });
AlertLog.belongsTo(DroneDetection, { foreignKey: 'detection_id', as: 'detection' });
// Tenant associations
Tenant.hasMany(User, { foreignKey: 'tenant_id', as: 'users' });
User.belongsTo(Tenant, { foreignKey: 'tenant_id', as: 'tenant' });
Tenant.hasMany(Device, { foreignKey: 'tenant_id', as: 'devices' });
Device.belongsTo(Tenant, { foreignKey: 'tenant_id', as: 'tenant' });
// Auto-sync database in test mode
if (process.env.NODE_ENV === 'test') {
sequelize.sync({ force: true }).then(() => {
console.log('🗄️ Test database tables created');
}).catch(error => {
console.error('❌ Test database sync failed:', error);
});
}
module.exports = {
sequelize,
Device,
DroneDetection,
Heartbeat,
User,
AlertRule,
AlertLog,
Tenant,
ManagementUser
};