From a2fb98102d0f7a31c543655979083e4841068df2 Mon Sep 17 00:00:00 2001 From: Fauzan Date: Thu, 23 Sep 2021 11:35:16 +0700 Subject: [PATCH] Add examples of associations #106 need more work with @papb --- .../sequelize/models/index.js | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 express-main-example/sequelize/models/index.js diff --git a/express-main-example/sequelize/models/index.js b/express-main-example/sequelize/models/index.js new file mode 100644 index 0000000..3a43fd1 --- /dev/null +++ b/express-main-example/sequelize/models/index.js @@ -0,0 +1,55 @@ +"use strict"; +const { Sequelize } = require("sequelize"); + +const db = {}; +const fs = require("fs"); +const path = require("path"); + +const sequelize = new Sequelize("xxxx", "xxxx", "xxxx", { + host: "xxxx", + port: "xxxx", + dialect: "xxxx", + logging: console.log, + benchmark: true, + timezone: "+00:00", +}); + +//Read all models in models folder +const modelDir = require("./"); +log( + "\u001b[33m", + "CRAWLING DATABASE MODEL DEFINITION in ", + modelDir, + "\u001b[39m" +); + +fs.readdirSync(modelDir) + .filter((file) => { + return file.indexOf(".") !== 0 && file.slice(-8) === "model.js"; + }) + .forEach((file) => { + let modelPath = path.join(modelDir, file); + let model = require(modelPath)(sequelize, Sequelize.DataTypes); + log( + "\u001b[36m", + "[MODEL FOUND]", + model, + " (", + modelPath, + ")", + "\u001b[39m" + ); + db[model.name] = model; + }); + +Object.keys(db).forEach((modelName) => { + console.log(db[modelName].associate); + // call the custom function + if (db[modelName].associate) db[modelName].associate(db); +}); + +// exports sequelize connection and Object +db.sequelize = sequelize; +db.Sequelize = Sequelize; + +module.exports = db;