Mise à jour de routes et models

This commit is contained in:
Rampeur
2025-08-10 09:15:18 +02:00
parent 61fdac2434
commit b68dd4c800
28 changed files with 1211 additions and 617 deletions
+103 -80
View File
@@ -1,25 +1,28 @@
var appEnv = process.env.APP_ENV;
if (appEnv == undefined) {
appEnv = 'development';
}
const dotenv = require("dotenv");
dotenv.config({ path: `.env.${appEnv}` });
require('dotenv').config({ path: `.env.${appEnv}` });
const { promisify } = require('util');
const express = require("express");
const sequelize = require("./util/database");
const chalk = require('chalk');
const morgan = require("morgan");
const colors = require("colors");
const utils = require('./routes/utils');
const { errorHandler } = require("./middlewares/errorHandler");
// Import Models
var isProduction = appEnv === 'production';
/*
var db = require("./models");
*/
// Import Models
const User = require("./models/User");
const Article = require("./models/Article");
const Tag = require("./models/Tag");
const Comment = require("./models/Comment");
*/
var db = require("./models/mysql");
const app = express();
@@ -27,31 +30,47 @@ const app = express();
app.use(express.json());
if (process.env.NODE_ENV === "development") {
app.use(morgan("dev"));
morgan.token('statusColor', (req, res) => {
let status = (typeof res.headersSent !== 'boolean' ? Boolean(res.header) : res.headersSent)
? res.statusCode
: undefined
return status >= 500 ? chalk.red(status)
: status >= 429 ? chalk.magenta(status)
: status >= 400 ? chalk.yellow(status)
: status >= 300 ? chalk.cyan(status)
: status >= 200 ? chalk.green(status)
: chalk.underline(status);
});
app.use(morgan('[:date[iso]] ":method :url HTTP/:http-version" :statusColor :res[content-length] ":referrer" ":user-agent" :remote-addr'));
//app.use(require('method-override')());
//app.use(express.static(__dirname + '/public'));
} else {
app.use(morgan('[:date[iso]] ":method :url HTTP/:http-version" :statusColor :res[content-length] ":referrer" ":user-agent" :remote-addr'));
app.use(morgan("dev"));
}
// CORS
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method === "OPTIONS") {
res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
return res.status(200).json({});
}
next();
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method === "OPTIONS") {
res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
return res.status(200).json({});
}
next();
});
// Route files
const users = require("./routes/users");
const profiles = require("./routes/profiles");
const articles = require("./routes/articles");
const comments = require("./routes/comments");
const tags = require("./routes/tags");
const users = require("./routes/api/users");
const profiles = require("./routes/api/profiles");
const articles = require("./routes/api/articles");
const comments = require("./routes/api/comments");
const tags = require("./routes/api/tags");
// Mount routers
app.use(users);
@@ -60,83 +79,87 @@ app.use(articles);
app.use(comments);
app.use(tags);
const PORT = process.env.PORT || process.env.SERVER_PORT;
//app.use(require('./routes'));
app.use(errorHandler);
console.log(`User: ${User}`);
// Relations
db.User.belongsToMany(User, {
as: "followers",
through: "Followers",
foreignKey: "userId",
timestamps: false,
});
db.User.belongsToMany(User, {
as: "following",
through: "Followers",
foreignKey: "followerId",
timestamps: false,
});
//console.log(`User: ${User}`);
db.User.hasMany(Article, {
foreignKey: "authorId",
onDelete: "CASCADE",
// Relations
User.belongsToMany(User, {
as: "followers",
through: "Followers",
foreignKey: "userId",
timestamps: false,
});
User.belongsToMany(User, {
as: "following",
through: "Followers",
foreignKey: "followerId",
timestamps: false,
});
User.hasMany(Article, {
foreignKey: "authorId",
onDelete: "CASCADE",
});
Article.belongsTo(User, { as: "author", foreignKey: "authorId" });
User.hasMany(Comment, {
foreignKey: "authorId",
onDelete: "CASCADE",
foreignKey: "authorId",
onDelete: "CASCADE",
});
Comment.belongsTo(User, { as: "author", foreignKey: "authorId" });
Article.hasMany(Comment, {
foreignKey: "articleId",
onDelete: "CASCADE",
foreignKey: "articleId",
onDelete: "CASCADE",
});
Comment.belongsTo(Article, { foreignKey: "articleId" });
User.belongsToMany(Article, {
as: "favorites",
through: "Favorites",
timestamps: false,
as: "favorites",
through: "Favorites",
timestamps: false,
});
Article.belongsToMany(User, {
through: "Favorites",
foreignKey: "articleId",
timestamps: false,
through: "Favorites",
foreignKey: "articleId",
timestamps: false,
});
Article.belongsToMany(Tag, {
through: "TagLists",
as: "tagLists",
foreignKey: "articleId",
timestamps: false,
onDelete: "CASCADE",
through: "TagLists",
as: "tagLists",
foreignKey: "articleId",
timestamps: false,
onDelete: "CASCADE",
});
Tag.belongsToMany(Article, {
through: "ArticleTags",
uniqueKey: false,
timestamps: false,
through: "ArticleTags",
uniqueKey: false,
timestamps: false,
});
/*
const sync = async () => await sequelize.sync({ force: true });
sync().then(() => {
User.create({
email: "test@test.com",
password: "123456",
username: "neo",
});
User.create({
email: "test2@test.com",
password: "123456",
username: "celeb_neo",
});
User.create({
email: "jgautier.webdev@gmail.com",
username: "adastra",
firstname: "Julien",
lastname: "Gautier",
password: "DKxp24PSnr",
role: "admin"
});
User.create({
email: "rampeur@gmail.com",
username: "solide",
firstname: "Rampeur",
lastname: "Solide",
password: "DKxp24PSnr",
role: "user"
});
});
*/
const startServer = async () => {
const port = process.env.SERVER_PORT || 3200;
await promisify(app.listen).bind(app)(port);
console.log(`${utils.getDateTimeISOString()}`, chalk.green(`${process.env.APP_ENV} API server listening on port ${port}`));
}
const server = app.listen(
PORT,
console.log(
`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold
)
);
// finally, let's start our server...
startServer();