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
+1 -1
View File
@@ -2,7 +2,7 @@ APP_ENV="development"
NODE_ENV="development" NODE_ENV="development"
DEBUG=false DEBUG=false
SERVER_PORT="3200" SERVER_PORT="3200"
SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO" JWT_SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
SESSION_LIFETIME="3600" SESSION_LIFETIME="3600"
SENDGRID_API_KEY="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" SENDGRID_API_KEY="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"
SENDGRID_FROM_MAIL="contact@rampeur.fr" SENDGRID_FROM_MAIL="contact@rampeur.fr"
+1 -1
View File
@@ -2,7 +2,7 @@ APP_ENV="development"
NODE_ENV="development" NODE_ENV="development"
DEBUG=false DEBUG=false
SERVER_PORT="3200" SERVER_PORT="3200"
SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO" JWT_SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
SESSION_LIFETIME=3600 SESSION_LIFETIME=3600
SENDGRID_API_KEY="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" SENDGRID_API_KEY="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"
SENDGRID_FROM_MAIL="contact@rampeur.fr" SENDGRID_FROM_MAIL="contact@rampeur.fr"
+1 -1
View File
@@ -2,7 +2,7 @@ APP_ENV="local"
NODE_ENV="development" NODE_ENV="development"
DEBUG=false DEBUG=false
SERVER_PORT="3200" SERVER_PORT="3200"
SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO" JWT_SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
SESSION_LIFETIME=3600 SESSION_LIFETIME=3600
SENDGRID_API_KEY="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" SENDGRID_API_KEY="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"
SENDGRID_FROM_MAIL="contact@rampeur.fr" SENDGRID_FROM_MAIL="contact@rampeur.fr"
+1 -1
View File
@@ -2,7 +2,7 @@ APP_ENV="production"
NODE_ENV="production" NODE_ENV="production"
DEBUG=false DEBUG=false
SERVER_PORT="3200" SERVER_PORT="3200"
SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO" JWT_SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
SESSION_LIFETIME=3600 SESSION_LIFETIME=3600
SENDGRID_API_KEY="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" SENDGRID_API_KEY="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"
SENDGRID_FROM_MAIL="contact@rampeur.fr" SENDGRID_FROM_MAIL="contact@rampeur.fr"
+6
View File
@@ -20,6 +20,8 @@ module.exports.getProfile = asyncHandler(async (req, res, next) => {
const profile = { const profile = {
username, username,
firstname: user.firstname,
lastname: user.lastname,
bio: user.bio, bio: user.bio,
image: user.image, image: user.image,
following: isFollowing, following: isFollowing,
@@ -42,6 +44,8 @@ module.exports.followUser = asyncHandler(async (req, res, next) => {
const profile = { const profile = {
username: username, username: username,
firstname: userToFollow.dataValues.firstname,
lastname: userToFollow.dataValues.lastname,
bio: userToFollow.dataValues.bio, bio: userToFollow.dataValues.bio,
image: userToFollow.dataValues.image, image: userToFollow.dataValues.image,
following: true, following: true,
@@ -65,6 +69,8 @@ module.exports.unfollowUser = asyncHandler(async (req, res, next) => {
const profile = { const profile = {
username: username, username: username,
firstname: userToUnfollow.dataValues.firstname,
lastname: userToUnfollow.dataValues.lastname,
bio: userToUnfollow.dataValues.bio, bio: userToUnfollow.dataValues.bio,
image: userToUnfollow.dataValues.image, image: userToUnfollow.dataValues.image,
following: false, following: false,
+5 -1
View File
@@ -4,16 +4,20 @@ const ErrorResponse = require("../util/errorResponse");
const { sign } = require("../util/jwt"); const { sign } = require("../util/jwt");
module.exports.createUser = asyncHandler(async (req, res, next) => { module.exports.createUser = asyncHandler(async (req, res, next) => {
const { email, password, username } = req.body.user; const { email, password, username, firstname, lastname } = req.body.user;
fieldValidation(email, next); fieldValidation(email, next);
fieldValidation(password, next); fieldValidation(password, next);
fieldValidation(username, next); fieldValidation(username, next);
fieldValidation(firstname, next);
fieldValidation(lastname, next);
const user = await User.create({ const user = await User.create({
email: email, email: email,
password: password, password: password,
username: username, username: username,
firstname: firstname,
lastname: lastname,
}); });
if (user.dataValues.password) { if (user.dataValues.password) {
-27
View File
@@ -1,27 +0,0 @@
const { DataTypes, Model } = require("sequelize");
const sequelize = require("../util/database");
const slugify = require("slugify");
const Article = sequelize.define("Article", {
slug: {
type: DataTypes.STRING,
allowNull: false,
},
title: {
type: DataTypes.STRING,
allowNull: false,
},
description: {
type: DataTypes.TEXT,
},
body: {
type: DataTypes.TEXT,
allowNull: false,
},
});
Article.beforeValidate((article) => {
article.slug = slugify(article.title, { lower: true });
});
module.exports = Article;
-11
View File
@@ -1,11 +0,0 @@
const { DataTypes, Model } = require("sequelize");
const sequelize = require("../util/database");
const Comment = sequelize.define("Comment", {
body: {
type: DataTypes.TEXT,
allowNull: false,
},
});
module.exports = Comment;
-16
View File
@@ -1,16 +0,0 @@
const { DataTypes, Model } = require("sequelize");
const sequelize = require("../util/database");
const Tag = sequelize.define(
"Tag",
{
name: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true,
},
},
{ timestamps: false }
);
module.exports = Tag;
-58
View File
@@ -1,58 +0,0 @@
const { DataTypes, Model } = require("sequelize");
const sequelize = require("../util/database");
const bcrypt = require("bcryptjs");
/**
* "email": "jake@jake.jake",
"token": "jwt.token.here",
"username": "jake",
"bio": "I work at statefarm",
"image": null
*/
const User = sequelize.define(
"User",
{
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
bio: {
type: DataTypes.TEXT,
allowNull: true,
},
image: {
type: DataTypes.TEXT,
allowNull: true,
},
},
{ timestamps: false }
);
Model.prototype.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};
const DEFAULT_SALT_ROUNDS = 10;
User.addHook("beforeCreate", async (user) => {
const encryptedPassword = await bcrypt.hash(
user.password,
DEFAULT_SALT_ROUNDS
);
user.password = encryptedPassword;
});
module.exports = User;
+16 -30
View File
@@ -1,26 +1,15 @@
const { DataTypes, Model } = require("sequelize");
const sequelize = require("../util/database");
const slugify = require("slugify"); const slugify = require("slugify");
//const slug = require("slug");
const { const Article = sequelize.define("Article", {
Model id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
} = require('sequelize'); slug: { type: DataTypes.STRING, allowNull: false },
module.exports = (sequelize, DataTypes) => { title: { type: DataTypes.STRING, allowNull: false },
class Article extends Model { description: { type: DataTypes.TEXT },
/** body: { type: DataTypes.TEXT, allowNull: false },
* Helper method for defining associations. createdAt: { type: DataTypes.DATE, allowNull: true },
* This method is not a part of Sequelize lifecycle. updatedAt: { type: DataTypes.DATE, allowNull: true }
* The `models/index` file will call this method automatically.
*/
static associate(models) {
/* define association here */
}
}
Article.init({
article_id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
article_slug: { type: DataTypes.STRING, allowNull: false },
article_title: { type: DataTypes.STRING, allowNull: false },
article_description: { type: DataTypes.TEXT },
article_body: { type: DataTypes.TEXT, allowNull: false }
}, { }, {
sequelize, sequelize,
timestamps: false, timestamps: false,
@@ -31,20 +20,17 @@ module.exports = (sequelize, DataTypes) => {
}); });
Article.beforeValidate((article) => { Article.beforeValidate((article) => {
//article.slug = slug(article.title) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
article.slug = slugify(article.title, { lower: true }); article.slug = slugify(article.title, { lower: true });
}); });
Article.prototype.toJSONFor = function () { Article.prototype.toJSONFor = function () {
return { return {
id: this.article_id, id: this.id,
slug: this.article_slug, slug: this.slug,
title: this.article_title, title: this.title,
description: this.article_description, description: this.description,
body: this.article_body body: this.body
}; };
}; };
return Article; module.exports = Article;
};
+11 -21
View File
@@ -1,20 +1,11 @@
const { const { DataTypes, Model } = require("sequelize");
Model const sequelize = require("../util/database");
} = require('sequelize');
module.exports = (sequelize, DataTypes) => { const Comment = sequelize.define("Comment", {
class Comment extends Model { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
/** body: { type: DataTypes.TEXT, allowNull: false },
* Helper method for defining associations. createdAt: { type: DataTypes.DATE, allowNull: true },
* This method is not a part of Sequelize lifecycle. updatedAt: { type: DataTypes.DATE, allowNull: true }
* The `models/index` file will call this method automatically.
*/
static associate(models) {
/* define association here */
}
}
Comment.init({
comment_id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
comment_body: { type: DataTypes.TEXT, allowNull: false }
}, { }, {
sequelize, sequelize,
timestamps: false, timestamps: false,
@@ -26,10 +17,9 @@ module.exports = (sequelize, DataTypes) => {
Comment.prototype.toJSONFor = function () { Comment.prototype.toJSONFor = function () {
return { return {
id: this.comment_id, id: this.id,
body: this.comment_body body: this.body
}; };
}; };
return Comment; module.exports = Comment;
};
+9 -20
View File
@@ -1,19 +1,10 @@
const { const { DataTypes, Model } = require("sequelize");
Model const sequelize = require("../util/database");
} = require('sequelize');
module.exports = (sequelize, DataTypes) => { const Tag = sequelize.define("Tag", {
class Tag extends Model { name: { type: DataTypes.STRING, primaryKey: true, allowNull: false },
/** createdAt: { type: DataTypes.DATE, allowNull: true },
* Helper method for defining associations. updatedAt: { type: DataTypes.DATE, allowNull: true }
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
/* define association here */
}
}
Tag.init({
tag_name: { type: DataTypes.STRING, allowNull: false, primaryKey: true }
}, { }, {
sequelize, sequelize,
timestamps: false, timestamps: false,
@@ -25,10 +16,8 @@ module.exports = (sequelize, DataTypes) => {
Tag.prototype.toJSONFor = function () { Tag.prototype.toJSONFor = function () {
return { return {
id: this.tag_id, name: this.name
name: this.tag_name
}; };
}; };
return Tag; module.exports = Tag;
};
+31 -44
View File
@@ -1,35 +1,27 @@
'use strict'; const { DataTypes, Model } = require("sequelize");
const sequelize = require("../util/database");
const bcrypt = require("bcryptjs"); const bcrypt = require("bcryptjs");
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
/** /**
* Helper method for defining associations. * "email": "jake@jake.jake",
* This method is not a part of Sequelize lifecycle. "token": "jwt.token.here",
* The `models/index` file will call this method automatically. "username": "jake",
"bio": "I work at statefarm",
"image": null
*/ */
static associate(models) {
/* define association here */ const User = sequelize.define("User", {
} id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
} email: { type: DataTypes.STRING, allowNull: false, unique: true },
User.init({ username: { type: DataTypes.STRING, allowNull: false, unique: true },
user_id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false}, firstname: { type: DataTypes.STRING },
user_username: {type: DataTypes.STRING, allowNull: false}, lastname: { type: DataTypes.STRING },
user_lastname: {type: DataTypes.STRING}, bio: { type: DataTypes.TEXT, allowNull: true },
user_firstname: {type: DataTypes.STRING}, image: { type: DataTypes.TEXT, allowNull: true },
user_email: {type: DataTypes.STRING}, role: { type: DataTypes.STRING },
user_adresse: {type: DataTypes.STRING}, password: { type: DataTypes.STRING, allowNull: false },
user_ville: {type: DataTypes.STRING}, createdAt: { type: DataTypes.DATE, allowNull: true },
user_region: {type: DataTypes.STRING}, updatedAt: { type: DataTypes.DATE, allowNull: true }
user_cp: {type: DataTypes.STRING},
user_pays: {type: DataTypes.STRING},
user_tel: {type: DataTypes.STRING},
user_mobile: {type: DataTypes.STRING},
user_role: {type: DataTypes.INTEGER}
}, { }, {
sequelize, sequelize,
timestamps: false, timestamps: false,
@@ -39,7 +31,7 @@ module.exports = (sequelize, DataTypes) => {
updatedAt: true updatedAt: true
}); });
User.prototype.matchPassword = async function (enteredPassword) { Model.prototype.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password); return await bcrypt.compare(enteredPassword, this.password);
}; };
@@ -55,20 +47,15 @@ module.exports = (sequelize, DataTypes) => {
User.prototype.toJSONFor = function () { User.prototype.toJSONFor = function () {
return { return {
id: this.mbr_id, id: this.id,
username: this.mbr_pseudo, email: this.email,
lastname: this.mbr_nom, username: this.username,
firstname: this.mbr_prenom, firstname: this.firstname,
email: this.mbr_email, lastname: this.lastname,
adresse: this.mbr_adresse, bio: this.bio,
ville: this.mbr_ville, image: this.image,
region: this.mbr_region, role: this.role
cp: this.mbr_cp,
pays: this.mbr_pays,
tel: this.mbr_tel,
mobile: this.mbr_mobile,
statut: this.mbr_statut
}; };
}; };
return User;
}; module.exports = User;
+10 -10
View File
@@ -16,11 +16,11 @@ module.exports = (sequelize, DataTypes) => {
} }
} }
Article.init({ Article.init({
article_id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false }, articleId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
article_slug: { type: DataTypes.STRING, allowNull: false }, slug: { type: DataTypes.STRING, allowNull: false },
article_title: { type: DataTypes.STRING, allowNull: false }, title: { type: DataTypes.STRING, allowNull: false },
article_description: { type: DataTypes.TEXT }, description: { type: DataTypes.TEXT },
article_body: { type: DataTypes.TEXT, allowNull: false } body: { type: DataTypes.TEXT, allowNull: false }
}, { }, {
sequelize, sequelize,
timestamps: false, timestamps: false,
@@ -36,11 +36,11 @@ module.exports = (sequelize, DataTypes) => {
Article.prototype.toJSONFor = function () { Article.prototype.toJSONFor = function () {
return { return {
id: this.article_id, articleId: this.articleId,
slug: this.article_slug, slug: this.slug,
title: this.article_title, title: this.title,
description: this.article_description, description: this.description,
body: this.article_body body: this.body
}; };
}; };
+4 -4
View File
@@ -13,8 +13,8 @@ module.exports = (sequelize, DataTypes) => {
} }
} }
Comment.init({ Comment.init({
comment_id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false }, commentId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
comment_body: { type: DataTypes.TEXT, allowNull: false } body: { type: DataTypes.TEXT, allowNull: false }
}, { }, {
sequelize, sequelize,
timestamps: false, timestamps: false,
@@ -26,8 +26,8 @@ module.exports = (sequelize, DataTypes) => {
Comment.prototype.toJSONFor = function () { Comment.prototype.toJSONFor = function () {
return { return {
id: this.comment_id, commentId: this.commentId,
body: this.comment_body body: this.body
}; };
}; };
+2 -3
View File
@@ -13,7 +13,7 @@ module.exports = (sequelize, DataTypes) => {
} }
} }
Tag.init({ Tag.init({
tag_name: { type: DataTypes.STRING, allowNull: false, primaryKey: true } name: { type: DataTypes.STRING, primaryKey: true, allowNull: false }
}, { }, {
sequelize, sequelize,
timestamps: false, timestamps: false,
@@ -25,8 +25,7 @@ module.exports = (sequelize, DataTypes) => {
Tag.prototype.toJSONFor = function () { Tag.prototype.toJSONFor = function () {
return { return {
id: this.tag_id, name: this.name
name: this.tag_name
}; };
}; };
+17 -26
View File
@@ -17,19 +17,15 @@ module.exports = (sequelize, DataTypes) => {
} }
} }
User.init({ User.init({
user_id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false}, userId: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false},
user_username: {type: DataTypes.STRING, allowNull: false}, email: {type: DataTypes.STRING, allowNull: false, unique: true},
user_lastname: {type: DataTypes.STRING}, username: {type: DataTypes.STRING, allowNull: false, unique: true},
user_firstname: {type: DataTypes.STRING}, firstname: {type: DataTypes.STRING},
user_email: {type: DataTypes.STRING}, lastname: {type: DataTypes.STRING},
user_adresse: {type: DataTypes.STRING}, bio: {type: DataTypes.TEXT, allowNull: true},
user_ville: {type: DataTypes.STRING}, image: {type: DataTypes.TEXT, allowNull: true},
user_region: {type: DataTypes.STRING}, role: {type: DataTypes.STRING},
user_cp: {type: DataTypes.STRING}, password: {type: DataTypes.STRING, allowNull: false}
user_pays: {type: DataTypes.STRING},
user_tel: {type: DataTypes.STRING},
user_mobile: {type: DataTypes.STRING},
user_role: {type: DataTypes.INTEGER}
}, { }, {
sequelize, sequelize,
timestamps: false, timestamps: false,
@@ -55,19 +51,14 @@ module.exports = (sequelize, DataTypes) => {
User.prototype.toJSONFor = function () { User.prototype.toJSONFor = function () {
return { return {
id: this.mbr_id, userId: this.userId,
username: this.mbr_pseudo, email: this.email,
lastname: this.mbr_nom, username: this.username,
firstname: this.mbr_prenom, firstname: this.firstname,
email: this.mbr_email, lastname: this.lastname,
adresse: this.mbr_adresse, bio: this.bio,
ville: this.mbr_ville, image: this.image,
region: this.mbr_region, role: this.role
cp: this.mbr_cp,
pays: this.mbr_pays,
tel: this.mbr_tel,
mobile: this.mbr_mobile,
statut: this.mbr_statut
}; };
}; };
return User; return User;
+1 -1
View File
@@ -4,7 +4,7 @@
"NODE_ENV" : "development", "NODE_ENV" : "development",
"DEBUG": false, "DEBUG": false,
"SERVER_PORT": "3200", "SERVER_PORT": "3200",
"SECRET": "$2b$10$aEsAUG7Dy8dcTORi1vaQle", "JWT_SECRET": "$2b$10$aEsAUG7Dy8dcTORi1vaQle",
"SESSION_LIFETIME": "3600", "SESSION_LIFETIME": "3600",
"MONGODB_URI": "mongodb://localhost:27017/adastradb", "MONGODB_URI": "mongodb://localhost:27017/adastradb",
"SENDGRID_API_KEY": "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", "SENDGRID_API_KEY": "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",
+826 -1
View File
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -34,6 +34,7 @@
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.0.0", "@eslint/js": "^9.0.0",
"eslint": "^9.0.0", "eslint": "^9.0.0",
"prettier": "^2.8.0" "prettier": "^2.8.0",
"sequelize-cli": "^6.6.3"
} }
} }
-30
View File
@@ -1,30 +0,0 @@
const express = require("express");
const router = express.Router();
const {
getArticle,
getArticles,
createArticle,
articlesFeed,
addFavoriteArticle,
deleteFavoriteArticle,
deleteArticle,
updateArticle,
} = require("../controllers/articles");
const { protect } = require("../middlewares/auth");
router
.route("/articles")
.get(protect, getArticles)
.post(protect, createArticle);
router.route("/articles/feed").get(protect, articlesFeed);
router
.route("/articles/:slug")
.get(protect, getArticle)
.put(protect, updateArticle)
.delete(protect, deleteArticle);
router
.route("/articles/:slug/favorite")
.post(protect, addFavoriteArticle)
.delete(protect, deleteFavoriteArticle);
module.exports = router;
-23
View File
@@ -1,23 +0,0 @@
const express = require("express");
const router = express.Router();
const {
getComment,
getComments,
createComment,
deleteComment,
} = require("../controllers/comments");
const { protect } = require("../middlewares/auth");
router
.route("/articles/:slug/comments")
.get(protect, getComments)
.post(protect, createComment);
router
.route("/articles/:slug/comments/:id")
.get(protect, getComment)
.delete(protect, deleteComment);
module.exports = router;
-16
View File
@@ -1,16 +0,0 @@
const express = require("express");
const router = express.Router();
const {
getProfile,
followUser,
unfollowUser,
} = require("../controllers/profiles");
const { protect } = require("../middlewares/auth");
router.route("/profiles/:username").get(protect, getProfile);
router
.route("/profiles/:username/follow")
.post(protect, followUser)
.delete(protect, unfollowUser);
module.exports = router;
-10
View File
@@ -1,10 +0,0 @@
const express = require("express");
const router = express.Router();
const { getTags } = require("../controllers/tags");
const { protect } = require("../middlewares/auth");
router.route("/tags/").get(getTags);
module.exports = router;
-16
View File
@@ -1,16 +0,0 @@
const express = require("express");
const router = express.Router();
const {
createUser,
loginUser,
getCurrentUser,
updateUser,
} = require("../controllers/users");
const { protect } = require("../middlewares/auth");
router.post("/users", createUser);
router.post("/users/login", loginUser);
router.route("/user").get(protect, getCurrentUser).put(protect, updateUser);
module.exports = router;
+59 -36
View File
@@ -1,25 +1,28 @@
var appEnv = process.env.APP_ENV; var appEnv = process.env.APP_ENV;
if (appEnv == undefined) { if (appEnv == undefined) {
appEnv = 'development'; appEnv = 'development';
} }
const dotenv = require("dotenv"); require('dotenv').config({ path: `.env.${appEnv}` });
dotenv.config({ path: `.env.${appEnv}` });
const { promisify } = require('util');
const express = require("express"); const express = require("express");
const sequelize = require("./util/database"); const sequelize = require("./util/database");
const chalk = require('chalk');
const morgan = require("morgan"); const morgan = require("morgan");
const colors = require("colors"); const colors = require("colors");
const utils = require('./routes/utils');
const { errorHandler } = require("./middlewares/errorHandler"); const { errorHandler } = require("./middlewares/errorHandler");
// Import Models var isProduction = appEnv === 'production';
/* /*
var db = require("./models");
*/
// Import Models
const User = require("./models/User"); const User = require("./models/User");
const Article = require("./models/Article"); const Article = require("./models/Article");
const Tag = require("./models/Tag"); const Tag = require("./models/Tag");
const Comment = require("./models/Comment"); const Comment = require("./models/Comment");
*/
var db = require("./models/mysql");
const app = express(); const app = express();
@@ -27,11 +30,26 @@ const app = express();
app.use(express.json()); app.use(express.json());
if (process.env.NODE_ENV === "development") { if (process.env.NODE_ENV === "development") {
app.use(morgan("dev")); morgan.token('statusColor', (req, res) => {
} else { 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(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("dev"));
} }
// CORS // CORS
app.use((req, res, next) => { app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Origin", "*");
@@ -46,12 +64,13 @@ app.use((req, res, next) => {
next(); next();
}); });
// Route files // Route files
const users = require("./routes/users"); const users = require("./routes/api/users");
const profiles = require("./routes/profiles"); const profiles = require("./routes/api/profiles");
const articles = require("./routes/articles"); const articles = require("./routes/api/articles");
const comments = require("./routes/comments"); const comments = require("./routes/api/comments");
const tags = require("./routes/tags"); const tags = require("./routes/api/tags");
// Mount routers // Mount routers
app.use(users); app.use(users);
@@ -60,42 +79,39 @@ app.use(articles);
app.use(comments); app.use(comments);
app.use(tags); app.use(tags);
const PORT = process.env.PORT || process.env.SERVER_PORT; //app.use(require('./routes'));
app.use(errorHandler); app.use(errorHandler);
console.log(`User: ${User}`); //console.log(`User: ${User}`);
// Relations // Relations
db.User.belongsToMany(User, { User.belongsToMany(User, {
as: "followers", as: "followers",
through: "Followers", through: "Followers",
foreignKey: "userId", foreignKey: "userId",
timestamps: false, timestamps: false,
}); });
db.User.belongsToMany(User, { User.belongsToMany(User, {
as: "following", as: "following",
through: "Followers", through: "Followers",
foreignKey: "followerId", foreignKey: "followerId",
timestamps: false, timestamps: false,
}); });
User.hasMany(Article, {
db.User.hasMany(Article, {
foreignKey: "authorId", foreignKey: "authorId",
onDelete: "CASCADE", onDelete: "CASCADE",
}); });
Article.belongsTo(User, { as: "author", foreignKey: "authorId" }); Article.belongsTo(User, { as: "author", foreignKey: "authorId" });
User.hasMany(Comment, { User.hasMany(Comment, {
foreignKey: "authorId", foreignKey: "authorId",
onDelete: "CASCADE", onDelete: "CASCADE",
}); });
Comment.belongsTo(User, { as: "author", foreignKey: "authorId" }); Comment.belongsTo(User, { as: "author", foreignKey: "authorId" });
Article.hasMany(Comment, { Article.hasMany(Comment, {
foreignKey: "articleId", foreignKey: "articleId",
onDelete: "CASCADE", onDelete: "CASCADE",
}); });
Comment.belongsTo(Article, { foreignKey: "articleId" }); Comment.belongsTo(Article, { foreignKey: "articleId" });
User.belongsToMany(Article, { User.belongsToMany(Article, {
as: "favorites", as: "favorites",
through: "Favorites", through: "Favorites",
@@ -106,7 +122,6 @@ Article.belongsToMany(User, {
foreignKey: "articleId", foreignKey: "articleId",
timestamps: false, timestamps: false,
}); });
Article.belongsToMany(Tag, { Article.belongsToMany(Tag, {
through: "TagLists", through: "TagLists",
as: "tagLists", as: "tagLists",
@@ -119,24 +134,32 @@ Tag.belongsToMany(Article, {
uniqueKey: false, uniqueKey: false,
timestamps: false, timestamps: false,
}); });
/*
const sync = async () => await sequelize.sync({ force: true }); const sync = async () => await sequelize.sync({ force: true });
sync().then(() => { sync().then(() => {
User.create({ User.create({
email: "test@test.com", email: "jgautier.webdev@gmail.com",
password: "123456", username: "adastra",
username: "neo", firstname: "Julien",
lastname: "Gautier",
password: "DKxp24PSnr",
role: "admin"
}); });
User.create({ User.create({
email: "test2@test.com", email: "rampeur@gmail.com",
password: "123456", username: "solide",
username: "celeb_neo", 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( // finally, let's start our server...
PORT, startServer();
console.log(
`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold
)
);
+1 -1
View File
@@ -2,7 +2,7 @@ const jwt = require("jsonwebtoken");
module.exports.sign = async (user) => { module.exports.sign = async (user) => {
const token = await jwt.sign( const token = await jwt.sign(
{ id: user.id, username: user.username, email: user.email }, { userId: user.userId, username: user.username, email: user.email },
process.env.JWT_SECRET process.env.JWT_SECRET
); );
return token; return token;