Mise à jour et ajout de controllers, routes, services et utilities
This commit is contained in:
+58
-17
@@ -5,25 +5,25 @@ const mongoose = require('mongoose');
|
||||
const DB = require('./mysql');
|
||||
const sequelize = require('./config/sequelize');
|
||||
const associate = require('./relationships');
|
||||
const utils = require('../utils');
|
||||
const DateUtilities = require('../utils/dateUtilities');
|
||||
|
||||
|
||||
|
||||
// Connect to the MongoDB database and log a message to the console
|
||||
const connectMongoDb = async () => {
|
||||
try {
|
||||
if (process.env.APP_ENV === 'production') {
|
||||
mongoose.connect(process.env.MONGODB_URI);
|
||||
await mongoose.connect(process.env.MONGODB_URI);
|
||||
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.green('MongoDB connection has been established successfully 🟢'));
|
||||
} else {
|
||||
mongoose.set('strictQuery', true);
|
||||
mongoose.connect(process.env.MONGODB_URI).then(() => {
|
||||
console.log(`${utils.getDateTimeISOString()}`, chalk.green('MongoDB connection has been established successfully 🟢'));
|
||||
}).catch(() => {
|
||||
console.log(`${utils.getDateTimeISOString()}`, chalk.red('Unable to connect to the MongoDB database 🔴'));
|
||||
});
|
||||
await mongoose.connect(process.env.MONGODB_URI);
|
||||
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.green('MongoDB connection has been established successfully 🟢'));
|
||||
mongoose.set('debug', process.env.DEBUG);
|
||||
console.log(`${utils.getDateTimeISOString()}`, chalk.red('debug :'), chalk.yellow(process.env.DEBUG));
|
||||
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.red('debug :'), chalk.yellow(process.env.DEBUG));
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`${utils.getDateTimeISOString()}`, chalk.red('Unable to connect to the MongoDB database 🔴'));
|
||||
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.red('Unable to connect to the MongoDB database 🔴'));
|
||||
console.error('MongoDB connection error:', error);
|
||||
// Exit the process if the connection is not successful
|
||||
process.exit(1);
|
||||
@@ -34,18 +34,54 @@ const connectMongoDb = async () => {
|
||||
const connectMysqlDb = async () => {
|
||||
try {
|
||||
await sequelize.authenticate();
|
||||
console.log(`${utils.getDateTimeISOString()}`, chalk.green('MySQL connection has been established successfully 🟢'));
|
||||
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.green('MySQL connection has been established successfully 🟢'));
|
||||
|
||||
// Synchronize the database with the models without need of dropping the tables
|
||||
await DB.sequelize.sync({
|
||||
force: false,
|
||||
// Check that required tables exist instead of synchronizing (no auto-create)
|
||||
const queryInterface = sequelize.getQueryInterface();
|
||||
let existingTables = [];
|
||||
try {
|
||||
existingTables = await queryInterface.showAllTables();
|
||||
} catch (err) {
|
||||
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.red('Unable to list tables from MySQL 🔴'));
|
||||
console.error(err);
|
||||
// Exit immediately if unable to list tables
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Build expected table list from models exported in DB
|
||||
const expectedTables = [];
|
||||
Object.keys(DB).forEach((key) => {
|
||||
const model = DB[key];
|
||||
if (model && typeof model.getTableName === 'function') {
|
||||
try {
|
||||
const t = model.getTableName();
|
||||
const tableName = typeof t === 'string' ? t : t.tableName;
|
||||
if (tableName) expectedTables.push(tableName);
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
} catch (err) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Call the associate function to create the relationships between the models
|
||||
// Normalize table names to strings for comparison
|
||||
const existingNormalized = existingTables.map(t => (typeof t === 'string' ? t : t.tableName)).map(t => t.toString());
|
||||
|
||||
const missing = expectedTables.filter(t => !existingNormalized.includes(t) && !existingNormalized.includes(t.toLowerCase()));
|
||||
|
||||
if (missing.length > 0) {
|
||||
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.red('Database schema validation failed - missing tables:'), chalk.yellow(missing.join(', ')));
|
||||
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.red('Run migrations to create the schema: npx sequelize-cli db:migrate'));
|
||||
// Exit immediately if schema is incomplete
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// If all expected tables are present, create associations
|
||||
associate();
|
||||
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.green('Database schema validated successfully 🟢'));
|
||||
|
||||
} catch (error) {
|
||||
console.log(`${utils.getDateTimeISOString()}`, chalk.red('Unable to connect to the MySQL database 🔴'));
|
||||
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.red('Unable to connect to the MySQL database 🔴'));
|
||||
console.error('MySQL connection error:', error);
|
||||
// Exit the process if the connection is not successful
|
||||
process.exit(1);
|
||||
@@ -55,8 +91,13 @@ const connectMysqlDb = async () => {
|
||||
|
||||
// Connect to all database and log a message to the console
|
||||
const connectAllDb = async () => {
|
||||
connectMongoDb();
|
||||
connectMysqlDb();
|
||||
try {
|
||||
await connectMongoDb();
|
||||
await connectMysqlDb();
|
||||
} catch (error) {
|
||||
console.error('Failed to connect to databases:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -63,7 +63,10 @@ const ArticleModel = () => {
|
||||
);
|
||||
|
||||
Article.beforeValidate((article) => {
|
||||
article.slug = slug(`${article.title}`) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
|
||||
if (!article.slug) {
|
||||
//article.slug = slug(`${article.title}`) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
|
||||
article.slug = slug(`${article.title}`);
|
||||
}
|
||||
});
|
||||
|
||||
Article.prototype.toJSONFor = function () {
|
||||
@@ -72,7 +75,14 @@ const ArticleModel = () => {
|
||||
slug: this.slug,
|
||||
title: this.title,
|
||||
description: this.description,
|
||||
body: this.body
|
||||
body: this.body,
|
||||
favorited: this.dataValues.favorited,
|
||||
favoritesCount: this.dataValues.favoritesCount,
|
||||
tagList: this.dataValues.tagList,
|
||||
articleTags: this.dataValues.articleTags,
|
||||
createdAt: this.createdAt,
|
||||
updatedAt: this.updatedAt,
|
||||
author: this.dataValues.author
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
var DataTypes = require("sequelize").DataTypes;
|
||||
var _Article = require("./Article");
|
||||
var _ArticleTag = require("./ArticleTag");
|
||||
var _Comment = require("./Comment");
|
||||
var _Favorite = require("./Favorite");
|
||||
var _Follower = require("./Follower");
|
||||
var _Tag = require("./Tag");
|
||||
var _TagList = require("./TagList");
|
||||
var _User = require("./User");
|
||||
|
||||
function initModels(sequelize) {
|
||||
var Article = _Article(sequelize, DataTypes);
|
||||
var ArticleTag = _ArticleTag(sequelize, DataTypes);
|
||||
var Comment = _Comment(sequelize, DataTypes);
|
||||
var Favorite = _Favorite(sequelize, DataTypes);
|
||||
var Follower = _Follower(sequelize, DataTypes);
|
||||
var Tag = _Tag(sequelize, DataTypes);
|
||||
var TagList = _TagList(sequelize, DataTypes);
|
||||
var User = _User(sequelize, DataTypes);
|
||||
|
||||
Article.belongsToMany(Tag, { as: 'tagNameTags', through: ArticleTag, foreignKey: "articleId", otherKey: "tagName" });
|
||||
Article.belongsToMany(Tag, { as: 'tagNameTagTagLists', through: TagList, foreignKey: "articleId", otherKey: "tagName" });
|
||||
Article.belongsToMany(User, { as: 'userIdUsers', through: Favorite, foreignKey: "articleId", otherKey: "userId" });
|
||||
Tag.belongsToMany(Article, { as: 'articleIdArticles', through: ArticleTag, foreignKey: "tagName", otherKey: "articleId" });
|
||||
Tag.belongsToMany(Article, { as: 'articleIdArticleTagLists', through: TagList, foreignKey: "tagName", otherKey: "articleId" });
|
||||
User.belongsToMany(Article, { as: 'articleIdArticleFavorites', through: Favorite, foreignKey: "userId", otherKey: "articleId" });
|
||||
User.belongsToMany(User, { as: 'followerIdUsers', through: Follower, foreignKey: "userId", otherKey: "followerId" });
|
||||
User.belongsToMany(User, { as: 'userIdUserFollowers', through: Follower, foreignKey: "followerId", otherKey: "userId" });
|
||||
ArticleTag.belongsTo(Article, { as: "article", foreignKey: "articleId"});
|
||||
Article.hasMany(ArticleTag, { as: "articleTags", foreignKey: "articleId"});
|
||||
Comment.belongsTo(Article, { as: "article", foreignKey: "articleId"});
|
||||
Article.hasMany(Comment, { as: "comments", foreignKey: "articleId"});
|
||||
Favorite.belongsTo(Article, { as: "article", foreignKey: "articleId"});
|
||||
Article.hasMany(Favorite, { as: "favorites", foreignKey: "articleId"});
|
||||
TagList.belongsTo(Article, { as: "article", foreignKey: "articleId"});
|
||||
Article.hasMany(TagList, { as: "tagLists", foreignKey: "articleId"});
|
||||
ArticleTag.belongsTo(Tag, { as: "tagNameTag", foreignKey: "tagName"});
|
||||
Tag.hasMany(ArticleTag, { as: "articleTags", foreignKey: "tagName"});
|
||||
TagList.belongsTo(Tag, { as: "tagNameTag", foreignKey: "tagName"});
|
||||
Tag.hasMany(TagList, { as: "tagLists", foreignKey: "tagName"});
|
||||
Article.belongsTo(User, { as: "author", foreignKey: "authorId"});
|
||||
User.hasMany(Article, { as: "articles", foreignKey: "authorId"});
|
||||
Comment.belongsTo(User, { as: "author", foreignKey: "authorId"});
|
||||
User.hasMany(Comment, { as: "comments", foreignKey: "authorId"});
|
||||
Favorite.belongsTo(User, { as: "user", foreignKey: "userId"});
|
||||
User.hasMany(Favorite, { as: "favorites", foreignKey: "userId"});
|
||||
Follower.belongsTo(User, { as: "user", foreignKey: "userId"});
|
||||
User.hasMany(Follower, { as: "followers", foreignKey: "userId"});
|
||||
Follower.belongsTo(User, { as: "follower", foreignKey: "followerId"});
|
||||
User.hasMany(Follower, { as: "followerFollowers", foreignKey: "followerId"});
|
||||
|
||||
return {
|
||||
Article,
|
||||
ArticleTag,
|
||||
Comment,
|
||||
Favorite,
|
||||
Follower,
|
||||
Tag,
|
||||
TagList,
|
||||
User
|
||||
};
|
||||
}
|
||||
module.exports = initModels;
|
||||
module.exports.initModels = initModels;
|
||||
module.exports.default = initModels;
|
||||
@@ -1,11 +1,11 @@
|
||||
const DB = require('../mysql');
|
||||
|
||||
const associate = () => {
|
||||
DB.Article.belongsToMany(DB.Tag, { as: 'articleTags', through: DB.TagList, foreignKey: "articleId", otherKey: "tagName" });
|
||||
DB.Article.belongsToMany(DB.User, { as: 'userIdUsers', through: DB.Favorite, foreignKey: "articleId", otherKey: "userId" });
|
||||
DB.Article.belongsToMany(DB.Tag, { as: 'articleTags', through: DB.TagList, foreignKey: "articleId", otherKey: "tagName", onDelete: "CASCADE" });
|
||||
DB.Product.belongsToMany(DB.Tag, { as: 'productTags', through: DB.ProductTagXref, foreignKey: "productId", otherKey: "tagName", onDelete: "CASCADE" });
|
||||
DB.Article.belongsToMany(DB.User, { as: 'articleFavoriteUsers', through: DB.Favorite, foreignKey: "articleId", otherKey: "userId", onDelete: "CASCADE" });
|
||||
DB.Category.belongsToMany(DB.Product, { as: 'productIdProducts', through: DB.ProductCategoryXref, foreignKey: "categoryId", otherKey: "productId" });
|
||||
DB.Product.belongsToMany(DB.Category, { as: 'productCategories', through: DB.ProductCategoryXref, foreignKey: "productId", otherKey: "categoryId" });
|
||||
DB.Product.belongsToMany(DB.Tag, { as: 'productTags', through: DB.ProductTagXref, foreignKey: "productId", otherKey: "tagName" });
|
||||
DB.Role.belongsToMany(DB.User, { as: 'userIdUserUserRoleXrefs', through: DB.UserRoleXref, foreignKey: "roleId", otherKey: "userId" });
|
||||
DB.Tag.belongsToMany(DB.Article, { as: 'articleIdArticleTagLists', through: DB.TagList, foreignKey: "tagName", otherKey: "articleId" });
|
||||
DB.Tag.belongsToMany(DB.Product, { as: 'productIdProductProductTagXrefs', through: DB.ProductTagXref, foreignKey: "tagName", otherKey: "productId" });
|
||||
@@ -14,11 +14,11 @@ const associate = () => {
|
||||
DB.User.belongsToMany(DB.User, { as: 'followerIdUsers', through: DB.Follower, foreignKey: "userId", otherKey: "followerId" });
|
||||
DB.User.belongsToMany(DB.User, { as: 'userIdUserFollowers', through: DB.Follower, foreignKey: "followerId", otherKey: "userId" });
|
||||
DB.Comment.belongsTo(DB.Article, { as: "article", foreignKey: "articleId"});
|
||||
DB.Article.hasMany(DB.Comment, { as: "comments", foreignKey: "articleId"});
|
||||
DB.Article.hasMany(DB.Comment, { as: "comments", foreignKey: "articleId", onDelete: "CASCADE"});
|
||||
DB.Favorite.belongsTo(DB.Article, { as: "article", foreignKey: "articleId"});
|
||||
DB.Article.hasMany(DB.Favorite, { as: "favorites", foreignKey: "articleId"});
|
||||
DB.Article.hasMany(DB.Favorite, { as: "favorites", foreignKey: "articleId", onDelete: "CASCADE"});
|
||||
DB.TagList.belongsTo(DB.Article, { as: "article", foreignKey: "articleId"});
|
||||
DB.Article.hasMany(DB.TagList, { as: "tagLists", foreignKey: "articleId"});
|
||||
DB.Article.hasMany(DB.TagList, { as: "tagLists", foreignKey: "articleId", onDelete: "CASCADE"});
|
||||
DB.Product.belongsTo(DB.Brand, { as: "brand", foreignKey: "brandId"});
|
||||
DB.Brand.hasMany(DB.Product, { as: "products", foreignKey: "brandId"});
|
||||
DB.ProductCategoryXref.belongsTo(DB.Category, { as: "category", foreignKey: "categoryId"});
|
||||
@@ -34,11 +34,11 @@ const associate = () => {
|
||||
DB.ProductTagXref.belongsTo(DB.Tag, { as: "tagNameTag", foreignKey: "tagName"});
|
||||
DB.Tag.hasMany(DB.ProductTagXref, { as: "productTagXrefs", foreignKey: "tagName"});
|
||||
DB.TagList.belongsTo(DB.Tag, { as: "tagNameTag", foreignKey: "tagName"});
|
||||
DB.Tag.hasMany(DB.TagList, { as: "tagLists", foreignKey: "tagName"});
|
||||
DB.Tag.hasMany(DB.TagList, { as: "tagLists", foreignKey: "tagName", onDelete: "CASCADE"});
|
||||
DB.Article.belongsTo(DB.User, { as: "author", foreignKey: "authorId"});
|
||||
DB.User.hasMany(DB.Article, { as: "articles", foreignKey: "authorId"});
|
||||
DB.User.hasMany(DB.Article, { as: "articles", foreignKey: "authorId", onDelete: "CASCADE"});
|
||||
DB.Comment.belongsTo(DB.User, { as: "author", foreignKey: "authorId"});
|
||||
DB.User.hasMany(DB.Comment, { as: "comments", foreignKey: "authorId"});
|
||||
DB.User.hasMany(DB.Comment, { as: "comments", foreignKey: "authorId", onDelete: "CASCADE"});
|
||||
DB.Favorite.belongsTo(DB.User, { as: "user", foreignKey: "userId"});
|
||||
DB.User.hasMany(DB.Favorite, { as: "favorites", foreignKey: "userId"});
|
||||
DB.Follower.belongsTo(DB.User, { as: "user", foreignKey: "userId"});
|
||||
|
||||
Reference in New Issue
Block a user