Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion app/config/db.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb"
DB: "testdb",
DIALECT: "mysql"
};
81 changes: 81 additions & 0 deletions app/config/db.init.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/**
Initialization script for database setup.

Usage:
Run this file once to create the database (and optionally the tables):
$ node ./app/config/db.init.js

By default, this script runs immediately when executed.
It does NOT export any functions since it’s meant to be a one-time setup.
If you prefer to import and call the functions manually elsewhere,
just uncomment the last line, and paste the following script in the desired file:

const { createDatabase, createTables } = require('./app/config/db.init');
createDatabase();
createTables();

*/

const { Sequelize } = require("sequelize");
const dbConfig = require("../config/db.config.js");

async function createDatabase() {
const sequelize = new Sequelize("", dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.DIALECT,
});

try {
await sequelize.query(`CREATE DATABASE IF NOT EXISTS \`${dbConfig.DB}\`;`);
console.log(`Database "${dbConfig.DB}" created successfully!`);

} catch (err) {
console.error("Error creating database:", err);

} finally {
await sequelize.close();
}
}

async function createTables() {
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.DIALECT,
});

// every table should be imported as it follows:
const { TutorialModel } = require("../models/tutorial.model.js");

// the model should be added to "modelNameList":
const modelNameList = [TutorialModel];

for (const modelDef of modelNameList) {
const attributes = modelDef.getAttributes();
sequelize.define(
modelDef.name,
attributes,
{
...(modelDef.options || {}),
tableName: modelDef.options?.tableName ?? modelDef.tableName
}
);
}

try {
await sequelize.sync({ force: true });
console.log(`All tables created/updated successfully in database "${dbConfig.DB}"!`);
} catch (err) {
console.error(`Failed to create tables:`, err);
} finally {
await sequelize.close();
}
}

async function init() {
await createDatabase();
await createTables();
}

init();

// module.exports = { createDatabase, createTables }; // uncomment line to export function
34 changes: 33 additions & 1 deletion app/models/tutorial.model.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const sql = require("./db.js");
const dbConfig = require("../config/db.config.js");
const { Sequelize, DataTypes } = require('sequelize');

// constructor
const Tutorial = function(tutorial) {
Expand All @@ -7,6 +9,35 @@ const Tutorial = function(tutorial) {
this.published = tutorial.published;
};

// connecting to database
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.DIALECT,
});

// example table definition (every table model should be exported in the last line)
const TutorialModel = sequelize.define('Tutorial', {
id: {
type: DataTypes.INTEGER(11),
primaryKey: true,
autoIncrement: true,
},
title: {
type: DataTypes.TEXT,
allowNull: false,
},
description: {
type: DataTypes.STRING,
},
published: {
type: DataTypes.BOOLEAN,
defaultValue: false,
}
}, {
tableName: 'tutorials',
timestamps: true,
});

Tutorial.create = (newTutorial, result) => {
sql.query("INSERT INTO tutorials SET ?", newTutorial, (err, res) => {
if (err) {
Expand Down Expand Up @@ -126,4 +157,5 @@ Tutorial.removeAll = result => {
});
};

module.exports = Tutorial;
// add here modules to export
module.exports = { Tutorial, TutorialModel };
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"mysql": "^2.18.1"
"mysql": "^2.18.1",
"mysql2": "^3.15.2",
"sequelize": "^6.37.7"
}
}