imaginar/models/index.js
2024-10-19 20:24:54 +09:00

67 lines
1.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const db = {};
// 必要な環境変数の確認
const requiredEnvVariables = ['DB_HOST', 'DB_PORT', 'DB_USER', 'DB_PASSWORD', 'DB_NAME'];
requiredEnvVariables.forEach((envVar) => {
if (!process.env[envVar]) {
throw new Error(`環境変数 ${envVar} が設定されていません。`);
}
});
// Sequelizeの初期化環境変数を使用
const sequelize = new Sequelize({
dialect: 'mysql',
host: process.env.DB_HOST,
port: process.env.DB_PORT,
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
logging: false, // SQLログを非表示にする
timezone: '+09:00' // JST (UTC+9)
});
// データベース接続
sequelize.authenticate()
.then(() => {
console.log('データベース接続に成功しました。');
})
.catch(err => {
console.error('データベース接続に失敗しました:', err);
throw err;
});
// モデルの読み込み
fs
.readdirSync(__dirname)
.filter(file => {
return (
file.indexOf('.') !== 0 &&
file !== basename &&
file.slice(-3) === '.js' &&
file.indexOf('.test.js') === -1
);
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});
// モデルの関連付け
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
// Sequelizeインスタンスのエクスポート
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;