Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b8edd76454 | |||
| 9bce9b714e | |||
| e741081966 | |||
| 2f78d85a27 | |||
| b68dd4c800 | |||
| 61fdac2434 | |||
| e83b2e831f | |||
| dd5dbbb0fe | |||
| 16b2de084b | |||
| d477cf239c | |||
| 9a534d5a17 |
@@ -0,0 +1,15 @@
|
||||
APP_ENV="development"
|
||||
NODE_ENV="development"
|
||||
DEBUG=false
|
||||
SERVER_PORT="3201"
|
||||
JWT_SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
|
||||
SESSION_LIFETIME="3600"
|
||||
SENDGRID_API_KEY="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"
|
||||
SENDGRID_FROM_MAIL="contact@rampeur.fr"
|
||||
SENDGRID_TO_MAIL="rampeur@gmail.com"
|
||||
MYSQL_DBNAME="c4adastracomdb2"
|
||||
MYSQL_DBUSER="c4adastracomu2"
|
||||
MYSQL_DBPASS="kbrnrt5jPK12"
|
||||
MYSQL_DBHOST="ns388640.ip-176-31-255.eu"
|
||||
MYSQL_DBPORT="3306"
|
||||
MYSQL_DBTYPE="mysql"
|
||||
@@ -0,0 +1,15 @@
|
||||
APP_ENV="development"
|
||||
NODE_ENV="development"
|
||||
DEBUG=false
|
||||
SERVER_PORT="3201"
|
||||
JWT_SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
|
||||
SESSION_LIFETIME=3600
|
||||
SENDGRID_API_KEY="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"
|
||||
SENDGRID_FROM_MAIL="contact@rampeur.fr"
|
||||
SENDGRID_TO_MAIL="rampeur@gmail.com"
|
||||
MYSQL_DBNAME="c4adastracomdb2"
|
||||
MYSQL_DBUSER="c4adastracomu2"
|
||||
MYSQL_DBPASS="kbrnrt5jPK12"
|
||||
MYSQL_DBHOST="ns388640.ip-176-31-255.eu"
|
||||
MYSQL_DBPORT="3306"
|
||||
MYSQL_DBTYPE="mysql"
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
APP_ENV="local"
|
||||
NODE_ENV="development"
|
||||
DEBUG=false
|
||||
SERVER_PORT="3201"
|
||||
JWT_SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
|
||||
SESSION_LIFETIME=3600
|
||||
SENDGRID_API_KEY="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"
|
||||
SENDGRID_FROM_MAIL="contact@rampeur.fr"
|
||||
SENDGRID_TO_MAIL="rampeur@gmail.com"
|
||||
MYSQL_DBNAME="c4adastracomdb2"
|
||||
MYSQL_DBUSER="c4adastracomu2"
|
||||
MYSQL_DBPASS="kbrnrt5jPK12"
|
||||
MYSQL_DBHOST="ns388640.ip-176-31-255.eu"
|
||||
MYSQL_DBPORT="3306"
|
||||
MYSQL_DBTYPE="mysql"
|
||||
@@ -0,0 +1,15 @@
|
||||
APP_ENV="production"
|
||||
NODE_ENV="production"
|
||||
DEBUG=false
|
||||
SERVER_PORT="3201"
|
||||
JWT_SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
|
||||
SESSION_LIFETIME=3600
|
||||
SENDGRID_API_KEY="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"
|
||||
SENDGRID_FROM_MAIL="contact@rampeur.fr"
|
||||
SENDGRID_TO_MAIL="rampeur@gmail.com"
|
||||
MYSQL_DBNAME="c4adastracomdb2"
|
||||
MYSQL_DBUSER="c4adastracomu2"
|
||||
MYSQL_DBPASS="kbrnrt5jPK12"
|
||||
MYSQL_DBHOST="ns388640.ip-176-31-255.eu"
|
||||
MYSQL_DBPORT="3306"
|
||||
MYSQL_DBTYPE="mysql"
|
||||
@@ -62,5 +62,3 @@ sonar.properties
|
||||
**/*.copy.ts
|
||||
**/*.copy.scss
|
||||
**/*.copy.html
|
||||
|
||||
middlewares
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
const { where } = require("sequelize");
|
||||
const asyncHandler = require("../middlewares/asyncHandler");
|
||||
const Article = require("../models/Article");
|
||||
const Tag = require("../models/Tag");
|
||||
const User = require("../models/User");
|
||||
const ErrorResponse = require("../util/errorResponse");
|
||||
const slugify = require("slugify");
|
||||
|
||||
const {
|
||||
appendFollowers,
|
||||
appendFavorites,
|
||||
appendTagList,
|
||||
} = require("../util/helpers");
|
||||
|
||||
const includeOptions = [
|
||||
{
|
||||
model: Tag,
|
||||
as: "tagLists",
|
||||
attributes: ["name"],
|
||||
through: { attributes: [] },
|
||||
},
|
||||
{ model: User, as: "author", attributes: { exclude: ["email", "password"] } },
|
||||
];
|
||||
|
||||
module.exports.getArticles = asyncHandler(async (req, res, next) => {
|
||||
const { tag, author, favorited, limit = 20, offset = 0 } = req.query;
|
||||
const { loggedUser } = req;
|
||||
|
||||
const searchOptions = {
|
||||
include: [
|
||||
{
|
||||
model: Tag,
|
||||
as: "tagLists",
|
||||
attributes: ["name"],
|
||||
through: { attributes: [] }, // ? this will remove the rows from the join table
|
||||
// where: tag ? { name: tag } : {},
|
||||
...(tag && { where: { name: tag } }),
|
||||
},
|
||||
{
|
||||
model: User,
|
||||
as: "author",
|
||||
attributes: { exclude: ["password", "email"] },
|
||||
// where: author ? { username: author } : {},
|
||||
...(author && { where: { username: author } }),
|
||||
},
|
||||
],
|
||||
limit: parseInt(limit),
|
||||
offset: parseInt(offset),
|
||||
order: [["createdAt", "DESC"]],
|
||||
distinct: true,
|
||||
};
|
||||
|
||||
let articles = { rows: [], count: 0 };
|
||||
|
||||
if (favorited) {
|
||||
const user = await User.findOne({ where: { username: favorited } });
|
||||
|
||||
articles.rows = await user.getFavorites(searchOptions);
|
||||
articles.count = await user.countFavorites();
|
||||
} else {
|
||||
articles = await Article.findAndCountAll(searchOptions);
|
||||
}
|
||||
|
||||
for (let article of articles.rows) {
|
||||
const articleTags = await article.getTagLists();
|
||||
// const articleTags = article.tagLists;
|
||||
appendTagList(articleTags, article);
|
||||
await appendFollowers(loggedUser, article);
|
||||
await appendFavorites(loggedUser, article);
|
||||
|
||||
delete article.dataValues.Favorites;
|
||||
}
|
||||
|
||||
res
|
||||
.status(200)
|
||||
.json({ articles: articles.rows, articlesCount: articles.count });
|
||||
});
|
||||
|
||||
module.exports.createArticle = asyncHandler(async (req, res, next) => {
|
||||
const { loggedUser } = req;
|
||||
|
||||
fieldValidation(req.body.article.title, next);
|
||||
fieldValidation(req.body.article.description, next);
|
||||
fieldValidation(req.body.article.body, next);
|
||||
|
||||
const { title, description, body, tagList } = req.body.article;
|
||||
const slug = slugify(title, { lower: true });
|
||||
const slugInDB = await Article.findOne({ where: { slug: slug } });
|
||||
if (slugInDB) next(new ErrorResponse("Title already exists", 400));
|
||||
|
||||
const article = await Article.create({
|
||||
title: title,
|
||||
description: description,
|
||||
body: body,
|
||||
});
|
||||
|
||||
for (const tag of tagList) {
|
||||
const tagInDB = await Tag.findByPk(tag.trim());
|
||||
|
||||
if (tagInDB) {
|
||||
await article.addTagList(tagInDB);
|
||||
} else if (tag.length > 2) {
|
||||
const newTag = await Tag.create({ name: tag.trim() });
|
||||
await article.addTagList(newTag);
|
||||
}
|
||||
}
|
||||
delete loggedUser.dataValues.token;
|
||||
|
||||
article.dataValues.tagList = tagList;
|
||||
article.setAuthor(loggedUser);
|
||||
article.dataValues.author = loggedUser;
|
||||
await appendFollowers(loggedUser, loggedUser);
|
||||
await appendFavorites(loggedUser, article);
|
||||
|
||||
res.status(201).json({ article });
|
||||
});
|
||||
|
||||
module.exports.deleteArticle = asyncHandler(async (req, res, next) => {
|
||||
const { slug } = req.params;
|
||||
const { loggedUser } = req;
|
||||
|
||||
const article = await Article.findOne({
|
||||
where: { slug: slug },
|
||||
include: includeOptions,
|
||||
});
|
||||
|
||||
if (!article) next(new ErrorResponse("Article not found", 404));
|
||||
|
||||
if (article.authorId !== loggedUser.id)
|
||||
return next(new ErrorResponse("Unauthorized", 401));
|
||||
|
||||
await article.destroy();
|
||||
|
||||
res.status(200).json({ article });
|
||||
});
|
||||
|
||||
module.exports.updateArticle = asyncHandler(async (req, res, next) => {
|
||||
const { slug } = req.params;
|
||||
const { loggedUser } = req;
|
||||
|
||||
const article = await Article.findOne({
|
||||
where: { slug: slug },
|
||||
include: includeOptions,
|
||||
});
|
||||
|
||||
if (!article) next(new ErrorResponse("Article not found", 404));
|
||||
|
||||
if (article.authorId !== loggedUser.id)
|
||||
return next(new ErrorResponse("Unauthorized", 401));
|
||||
|
||||
const { title, description, body } = req.body.article;
|
||||
|
||||
const slugInDB = await Article.findOne({
|
||||
where: { slug: slugify(title ? title : article.title, { lower: true }) },
|
||||
});
|
||||
|
||||
if (slugInDB && slugInDB.slug !== slug)
|
||||
return next(new ErrorResponse("Title already exists", 400));
|
||||
|
||||
await article.update({
|
||||
title: title ? title : article.title,
|
||||
description: description ? description : article.description,
|
||||
body: body ? body : article.body,
|
||||
});
|
||||
|
||||
const articleTags = await article.getTagLists();
|
||||
appendTagList(articleTags, article);
|
||||
await appendFollowers(loggedUser, article);
|
||||
await appendFavorites(loggedUser, article);
|
||||
|
||||
res.status(200).json({ article });
|
||||
});
|
||||
|
||||
module.exports.articlesFeed = asyncHandler(async (req, res, next) => {
|
||||
const { loggedUser } = req;
|
||||
|
||||
const { limit = 3, offset = 0 } = req.query;
|
||||
const authors = await loggedUser.getFollowing();
|
||||
|
||||
const articles = await Article.findAndCountAll({
|
||||
include: includeOptions,
|
||||
limit: parseInt(limit),
|
||||
offset: offset * limit,
|
||||
order: [["createdAt", "DESC"]],
|
||||
where: { authorId: authors.map((author) => author.id) },
|
||||
distinct: true,
|
||||
});
|
||||
|
||||
for (const article of articles.rows) {
|
||||
const articleTags = await article.getTagLists();
|
||||
|
||||
appendTagList(articleTags, article);
|
||||
await appendFollowers(loggedUser, article);
|
||||
await appendFavorites(loggedUser, article);
|
||||
}
|
||||
|
||||
res.json({ articles: articles.rows, articlesCount: articles.count });
|
||||
});
|
||||
|
||||
module.exports.getArticle = asyncHandler(async (req, res, next) => {
|
||||
const { loggedUser } = req;
|
||||
const { slug } = req.params;
|
||||
|
||||
const article = await Article.findOne({
|
||||
where: { slug: slug },
|
||||
include: includeOptions,
|
||||
});
|
||||
|
||||
if (!article) return next(new ErrorResponse("Article not found", 404));
|
||||
|
||||
const articleTags = await article.getTagLists();
|
||||
appendTagList(articleTags, article);
|
||||
await appendFollowers(loggedUser, article);
|
||||
await appendFavorites(loggedUser, article);
|
||||
|
||||
res.status(200).json({ article });
|
||||
});
|
||||
|
||||
module.exports.addFavoriteArticle = asyncHandler(async (req, res, next) => {
|
||||
const { loggedUser } = req;
|
||||
const { slug } = req.params;
|
||||
|
||||
const article = await Article.findOne({
|
||||
where: { slug: slug },
|
||||
include: includeOptions,
|
||||
});
|
||||
|
||||
if (!article) return next(new ErrorResponse("Article not found", 404));
|
||||
|
||||
await loggedUser.addFavorite(article);
|
||||
|
||||
const articleTags = await article.getTagLists();
|
||||
appendTagList(articleTags, article);
|
||||
await appendFollowers(loggedUser, article);
|
||||
await appendFavorites(loggedUser, article);
|
||||
|
||||
res.status(200).json({ article });
|
||||
});
|
||||
|
||||
module.exports.deleteFavoriteArticle = asyncHandler(async (req, res, next) => {
|
||||
const { loggedUser } = req;
|
||||
const { slug } = req.params;
|
||||
|
||||
const article = await Article.findOne({
|
||||
where: { slug: slug },
|
||||
include: includeOptions,
|
||||
});
|
||||
|
||||
if (!article) return next(new ErrorResponse("Article not found", 404));
|
||||
|
||||
await loggedUser.removeFavorite(article);
|
||||
|
||||
const articleTags = await article.getTagLists();
|
||||
appendTagList(articleTags, article);
|
||||
await appendFollowers(loggedUser, article);
|
||||
await appendFavorites(loggedUser, article);
|
||||
|
||||
res.status(200).json({ article });
|
||||
});
|
||||
|
||||
const fieldValidation = (field, next) => {
|
||||
if (!field) {
|
||||
return next(new ErrorResponse(`Missing fields`, 400));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,120 @@
|
||||
const Comment = require("../models/Comment");
|
||||
const Article = require("../models/Article");
|
||||
const User = require("../models/User");
|
||||
const asyncHandler = require("../middlewares/asyncHandler");
|
||||
const { appendFollowers } = require("../util/helpers");
|
||||
const ErrorResponse = require("../util/errorResponse");
|
||||
|
||||
module.exports.getComments = asyncHandler(async (req, res, next) => {
|
||||
const { slug } = req.params;
|
||||
const { loggedUser } = req;
|
||||
|
||||
const article = await Article.findOne({
|
||||
where: { slug: slug },
|
||||
});
|
||||
|
||||
if (!article) return next(new ErrorResponse("Article not found", 404));
|
||||
|
||||
const comments = await article.getComments({
|
||||
include: [
|
||||
{
|
||||
model: User,
|
||||
as: "author",
|
||||
attributes: ["username", "bio", "image"],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
for (let comment of comments) {
|
||||
await appendFollowers(loggedUser, comment);
|
||||
}
|
||||
|
||||
res.status(200).json({ comments });
|
||||
});
|
||||
|
||||
module.exports.getComment = asyncHandler(async (req, res, next) => {
|
||||
const { slug, id } = req.params;
|
||||
const { loggedUser } = req;
|
||||
|
||||
const article = await Article.findOne({
|
||||
where: { slug: slug },
|
||||
});
|
||||
|
||||
if (!article) return next(new ErrorResponse("Article not found", 404));
|
||||
|
||||
const comment = await Comment.findOne({
|
||||
where: { id: id },
|
||||
include: [
|
||||
{
|
||||
model: User,
|
||||
as: "author",
|
||||
attributes: ["username", "bio", "image"],
|
||||
},
|
||||
],
|
||||
});
|
||||
if (!comment) return next(new ErrorResponse("Comment not found", 404));
|
||||
|
||||
await appendFollowers(loggedUser, comment);
|
||||
|
||||
res.status(200).json({ comment });
|
||||
});
|
||||
|
||||
module.exports.createComment = asyncHandler(async (req, res, next) => {
|
||||
const { body } = req.body.comment;
|
||||
const { slug } = req.params;
|
||||
const { loggedUser } = req;
|
||||
|
||||
fieldValidation(body, next);
|
||||
|
||||
const article = await Article.findOne({
|
||||
where: { slug: slug },
|
||||
include: [
|
||||
{ model: User, as: "author", attributes: ["username", "bio", "image"] },
|
||||
],
|
||||
});
|
||||
|
||||
if (!article) return next(new ErrorResponse("Article not found", 404));
|
||||
|
||||
const comment = await Comment.create({
|
||||
body: body,
|
||||
articleId: article.id,
|
||||
authorId: loggedUser.id,
|
||||
});
|
||||
|
||||
delete loggedUser.dataValues.token;
|
||||
await appendFollowers(loggedUser, loggedUser);
|
||||
|
||||
comment.dataValues.author = loggedUser;
|
||||
|
||||
res.status(201).json({ comment });
|
||||
});
|
||||
|
||||
module.exports.deleteComment = asyncHandler(async (req, res, next) => {
|
||||
const { slug, id } = req.params;
|
||||
const { loggedUser } = req;
|
||||
|
||||
const article = await Article.findOne({
|
||||
where: { slug: slug },
|
||||
});
|
||||
|
||||
if (!article) return next(new ErrorResponse("Article not found", 404));
|
||||
|
||||
const comment = await Comment.findOne({
|
||||
where: { id: id },
|
||||
});
|
||||
|
||||
if (!comment) return next(new ErrorResponse("Comment not found", 404));
|
||||
|
||||
if (comment.authorId !== loggedUser.id)
|
||||
return next(new ErrorResponse("Unauthorized", 401));
|
||||
|
||||
await comment.destroy();
|
||||
|
||||
res.status(200).json({ comment });
|
||||
});
|
||||
|
||||
const fieldValidation = (field, next) => {
|
||||
if (!field) {
|
||||
return next(new ErrorResponse(`Missing fields`, 400));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,80 @@
|
||||
const User = require("../models/User");
|
||||
const asyncHandler = require("../middlewares/asyncHandler");
|
||||
const ErrorResponse = require("../util/errorResponse");
|
||||
|
||||
module.exports.getProfile = asyncHandler(async (req, res, next) => {
|
||||
const username = req.params.username;
|
||||
const { loggedUser } = req;
|
||||
const user = await User.findOne({ where: { username: username } });
|
||||
|
||||
if (!user) {
|
||||
return next(new ErrorResponse(`User not found`, 404));
|
||||
}
|
||||
|
||||
let isFollowing = false;
|
||||
|
||||
if (loggedUser) {
|
||||
const followers = await user.getFollowers();
|
||||
isFollowing = followers.some((user) => user.id === loggedUser.id);
|
||||
}
|
||||
|
||||
const profile = {
|
||||
username,
|
||||
firstname: user.firstname,
|
||||
lastname: user.lastname,
|
||||
bio: user.bio,
|
||||
image: user.image,
|
||||
following: isFollowing,
|
||||
};
|
||||
res.status(200).json({ profile });
|
||||
});
|
||||
|
||||
module.exports.followUser = asyncHandler(async (req, res, next) => {
|
||||
const username = req.params.username;
|
||||
const { loggedUser } = req;
|
||||
const userToFollow = await User.findOne({ where: { username: username } });
|
||||
|
||||
if (!userToFollow) {
|
||||
return next(new ErrorResponse(`User not found`, 404));
|
||||
}
|
||||
|
||||
const currentUser = await User.findByPk(loggedUser.id);
|
||||
|
||||
await userToFollow.addFollower(currentUser);
|
||||
|
||||
const profile = {
|
||||
username: username,
|
||||
firstname: userToFollow.dataValues.firstname,
|
||||
lastname: userToFollow.dataValues.lastname,
|
||||
bio: userToFollow.dataValues.bio,
|
||||
image: userToFollow.dataValues.image,
|
||||
following: true,
|
||||
};
|
||||
|
||||
res.status(200).json({ profile });
|
||||
});
|
||||
|
||||
module.exports.unfollowUser = asyncHandler(async (req, res, next) => {
|
||||
const username = req.params.username;
|
||||
const { loggedUser } = req;
|
||||
const userToUnfollow = await User.findOne({ where: { username: username } });
|
||||
|
||||
if (!userToUnfollow) {
|
||||
return next(new ErrorResponse(`User not found`, 404));
|
||||
}
|
||||
|
||||
const currentUser = await User.findByPk(loggedUser.id);
|
||||
|
||||
await userToUnfollow.removeFollower(currentUser);
|
||||
|
||||
const profile = {
|
||||
username: username,
|
||||
firstname: userToUnfollow.dataValues.firstname,
|
||||
lastname: userToUnfollow.dataValues.lastname,
|
||||
bio: userToUnfollow.dataValues.bio,
|
||||
image: userToUnfollow.dataValues.image,
|
||||
following: false,
|
||||
};
|
||||
|
||||
res.status(200).json({ profile });
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
const Tag = require("../models/Tag");
|
||||
const { appendTagList } = require("../util/helpers");
|
||||
|
||||
module.exports.getTags = async (req, res, next) => {
|
||||
let tags = await Tag.findAll({
|
||||
attributes: ["name"],
|
||||
});
|
||||
|
||||
tags = tags.map((tag) => tag.name);
|
||||
|
||||
res.status(200).json({ tags });
|
||||
};
|
||||
@@ -0,0 +1,97 @@
|
||||
const asyncHandler = require("../middlewares/asyncHandler");
|
||||
const User = require("../models/User");
|
||||
const ErrorResponse = require("../util/errorResponse");
|
||||
const { sign } = require("../util/jwt");
|
||||
|
||||
module.exports.createUser = asyncHandler(async (req, res, next) => {
|
||||
const { email, password, username, firstname, lastname } = req.body.user;
|
||||
|
||||
fieldValidation(email, next);
|
||||
fieldValidation(password, next);
|
||||
fieldValidation(username, next);
|
||||
fieldValidation(firstname, next);
|
||||
fieldValidation(lastname, next);
|
||||
|
||||
const user = await User.create({
|
||||
email: email,
|
||||
password: password,
|
||||
username: username,
|
||||
firstname: firstname,
|
||||
lastname: lastname,
|
||||
});
|
||||
|
||||
if (user.dataValues.password) {
|
||||
delete user.dataValues.password;
|
||||
}
|
||||
|
||||
user.dataValues.token = await sign(user);
|
||||
|
||||
user.dataValues.bio = null;
|
||||
user.dataValues.image = null;
|
||||
|
||||
res.status(201).json({ user });
|
||||
});
|
||||
|
||||
module.exports.loginUser = asyncHandler(async (req, res, next) => {
|
||||
const { email, password } = req.body.user;
|
||||
|
||||
fieldValidation(email, next);
|
||||
fieldValidation(password, next);
|
||||
|
||||
const user = await User.findOne({
|
||||
where: {
|
||||
email: email,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return next(new ErrorResponse(`User not found`, 404));
|
||||
}
|
||||
|
||||
const isMatch = user.matchPassword(password);
|
||||
|
||||
if (!isMatch) {
|
||||
return next(new ErrorResponse("Wrong password", 401));
|
||||
}
|
||||
|
||||
delete user.dataValues.password;
|
||||
|
||||
user.dataValues.token = await sign(user);
|
||||
|
||||
user.dataValues.bio = null;
|
||||
user.dataValues.image = null;
|
||||
|
||||
res.status(200).json({ user });
|
||||
});
|
||||
|
||||
module.exports.getCurrentUser = asyncHandler(async (req, res, next) => {
|
||||
const { loggedUser } = req;
|
||||
const user = await User.findByPk(loggedUser.id);
|
||||
|
||||
if (!user) {
|
||||
return next(new ErrorResponse(`User not found`, 404));
|
||||
}
|
||||
|
||||
user.dataValues.token = req.headers.authorization.split(" ")[1];
|
||||
|
||||
res.status(200).json({ user });
|
||||
});
|
||||
|
||||
module.exports.updateUser = asyncHandler(async (req, res, next) => {
|
||||
await User.update(req.body.user, {
|
||||
where: {
|
||||
id: req.user.id,
|
||||
},
|
||||
});
|
||||
|
||||
const user = await User.findByPk(req.user.id);
|
||||
user.dataValues.token = req.headers.authorization.split(" ")[1];
|
||||
|
||||
res.status(200).json({ user });
|
||||
});
|
||||
|
||||
const fieldValidation = (field, next) => {
|
||||
if (!field) {
|
||||
return next(new ErrorResponse(`Missing fields`, 400));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
import globals from "globals";
|
||||
import pluginJs from "@eslint/js";
|
||||
|
||||
|
||||
export default [
|
||||
{files: ["**/*.js"], languageOptions: {sourceType: "commonjs"}},
|
||||
{languageOptions: { globals: globals.node }},
|
||||
pluginJs.configs.recommended,
|
||||
];
|
||||
@@ -0,0 +1,7 @@
|
||||
const asyncHandler = (fn) => (req, res, next) => {
|
||||
Promise.resolve(fn(req, res, next)).catch((err) => {
|
||||
next(err);
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = asyncHandler;
|
||||
@@ -0,0 +1,30 @@
|
||||
const { verify } = require("../util/jwt");
|
||||
const User = require("../models/User");
|
||||
const ErrorResponse = require("../util/errorResponse");
|
||||
|
||||
exports.protect = async (req, res, next) => {
|
||||
try {
|
||||
const { headers } = req;
|
||||
if (!headers.authorization) return next();
|
||||
|
||||
const token = headers.authorization.split(" ")[1];
|
||||
if (!token) throw new SyntaxError("Token missing or malformed");
|
||||
|
||||
const userVerified = await verify(token);
|
||||
if (!userVerified) throw new Error("Invalid Token");
|
||||
|
||||
req.loggedUser = await User.findOne({
|
||||
attributes: { exclude: ["email", "password"] },
|
||||
where: { email: userVerified.email },
|
||||
});
|
||||
|
||||
if (!req.loggedUser) next(new NotFoundError("User"));
|
||||
|
||||
headers.email = userVerified.email;
|
||||
req.loggedUser.dataValues.token = token;
|
||||
|
||||
next();
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
const ErrorResponse = require("../util/errorResponse");
|
||||
|
||||
//REQUESTED PAGE IS NOT FOUND
|
||||
module.exports.notFound = (req, res, next) => {
|
||||
const error = new ErrorResponse(`Not Found - ${req.originalUrl}`);
|
||||
res.status(404);
|
||||
next(error);
|
||||
};
|
||||
|
||||
module.exports.errorHandler = (err, req, res, next) => {
|
||||
// Log to console for dev
|
||||
console.log(err.message.red);
|
||||
console.log(err.stack.red);
|
||||
|
||||
const statusCode = err.statusCode ? err.statusCode : 500;
|
||||
|
||||
res.status(statusCode).json({
|
||||
errors: {
|
||||
body: [err.message],
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
const { DataTypes } = require("sequelize");
|
||||
const sequelize = require("../util/database");
|
||||
const slugify = require("slugify");
|
||||
|
||||
const Article = sequelize.define("Article", {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
|
||||
slug: { type: DataTypes.STRING, allowNull: false },
|
||||
title: { type: DataTypes.STRING, allowNull: false },
|
||||
description: { type: DataTypes.TEXT },
|
||||
body: { type: DataTypes.TEXT, allowNull: false }
|
||||
}, {
|
||||
sequelize,
|
||||
timestamps: true,
|
||||
modelName: 'Article',
|
||||
tableName: 'article',
|
||||
createdAt: true,
|
||||
updatedAt: true
|
||||
});
|
||||
|
||||
Article.beforeValidate((article) => {
|
||||
article.slug = slugify(article.title, { lower: true });
|
||||
});
|
||||
|
||||
Article.prototype.toJSONFor = function () {
|
||||
return {
|
||||
id: this.id,
|
||||
slug: this.slug,
|
||||
title: this.title,
|
||||
description: this.description,
|
||||
body: this.body
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = Article;
|
||||
@@ -0,0 +1,23 @@
|
||||
const { DataTypes } = require("sequelize");
|
||||
const sequelize = require("../util/database");
|
||||
|
||||
const Comment = sequelize.define("Comment", {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
|
||||
body: { type: DataTypes.TEXT, allowNull: false }
|
||||
}, {
|
||||
sequelize,
|
||||
timestamps: true,
|
||||
modelName: 'Comment',
|
||||
tableName: 'comment',
|
||||
createdAt: true,
|
||||
updatedAt: true
|
||||
});
|
||||
|
||||
Comment.prototype.toJSONFor = function () {
|
||||
return {
|
||||
id: this.id,
|
||||
body: this.body
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = Comment;
|
||||
@@ -0,0 +1,21 @@
|
||||
const { DataTypes } = require("sequelize");
|
||||
const sequelize = require("../util/database");
|
||||
|
||||
const Tag = sequelize.define("Tag", {
|
||||
name: { type: DataTypes.STRING, primaryKey: true, allowNull: false }
|
||||
}, {
|
||||
sequelize,
|
||||
timestamps: true,
|
||||
modelName: 'Tag',
|
||||
tableName: 'tag',
|
||||
createdAt: true,
|
||||
updatedAt: true
|
||||
});
|
||||
|
||||
Tag.prototype.toJSONFor = function () {
|
||||
return {
|
||||
name: this.name
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = Tag;
|
||||
@@ -0,0 +1,52 @@
|
||||
const { DataTypes, Model } = require("sequelize");
|
||||
|
||||
const sequelize = require("../util/database");
|
||||
const bcrypt = require("bcryptjs");
|
||||
|
||||
const User = sequelize.define("User", {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
|
||||
email: { type: DataTypes.STRING, allowNull: false, unique: true },
|
||||
username: { type: DataTypes.STRING, allowNull: false, unique: true },
|
||||
firstname: { type: DataTypes.STRING },
|
||||
lastname: { type: DataTypes.STRING },
|
||||
bio: { type: DataTypes.TEXT, allowNull: true },
|
||||
image: { type: DataTypes.TEXT, allowNull: true },
|
||||
role: { type: DataTypes.STRING },
|
||||
password: { type: DataTypes.STRING, allowNull: false }
|
||||
}, {
|
||||
sequelize,
|
||||
timestamps: true,
|
||||
modelName: 'User',
|
||||
tableName: 'user',
|
||||
createdAt: true,
|
||||
updatedAt: true
|
||||
});
|
||||
|
||||
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;
|
||||
});
|
||||
|
||||
User.prototype.toJSONFor = function () {
|
||||
return {
|
||||
id: this.id,
|
||||
email: this.email,
|
||||
username: this.username,
|
||||
firstname: this.firstname,
|
||||
lastname: this.lastname,
|
||||
bio: this.bio,
|
||||
image: this.image,
|
||||
role: this.role
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = User;
|
||||
@@ -0,0 +1,4 @@
|
||||
exports.User = require('./User');
|
||||
exports.Article = require('./Article');
|
||||
exports.Comment = require('./Comment');
|
||||
exports.Tag = require('./Tag');
|
||||
@@ -0,0 +1,48 @@
|
||||
|
||||
const slugify = require("slugify");
|
||||
|
||||
const {
|
||||
Model
|
||||
} = require('sequelize');
|
||||
module.exports = (sequelize, DataTypes) => {
|
||||
class Article extends Model {
|
||||
/**
|
||||
* Helper method for defining associations.
|
||||
* This method is not a part of Sequelize lifecycle.
|
||||
* The `models/index` file will call this method automatically.
|
||||
*/
|
||||
static associate(models) {
|
||||
/* define association here */
|
||||
}
|
||||
}
|
||||
Article.init({
|
||||
articleId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
|
||||
slug: { type: DataTypes.STRING, allowNull: false },
|
||||
title: { type: DataTypes.STRING, allowNull: false },
|
||||
description: { type: DataTypes.TEXT },
|
||||
body: { type: DataTypes.TEXT, allowNull: false }
|
||||
}, {
|
||||
sequelize,
|
||||
timestamps: false,
|
||||
modelName: 'Article',
|
||||
tableName: 'article',
|
||||
createdAt: true,
|
||||
updatedAt: true
|
||||
});
|
||||
|
||||
Article.beforeValidate((article) => {
|
||||
article.slug = slugify(article.title, { lower: true });
|
||||
});
|
||||
|
||||
Article.prototype.toJSONFor = function () {
|
||||
return {
|
||||
articleId: this.articleId,
|
||||
slug: this.slug,
|
||||
title: this.title,
|
||||
description: this.description,
|
||||
body: this.body
|
||||
};
|
||||
};
|
||||
|
||||
return Article;
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
const {
|
||||
Model
|
||||
} = require('sequelize');
|
||||
module.exports = (sequelize, DataTypes) => {
|
||||
class Comment extends Model {
|
||||
/**
|
||||
* Helper method for defining associations.
|
||||
* This method is not a part of Sequelize lifecycle.
|
||||
* The `models/index` file will call this method automatically.
|
||||
*/
|
||||
static associate(models) {
|
||||
/* define association here */
|
||||
}
|
||||
}
|
||||
Comment.init({
|
||||
commentId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
|
||||
body: { type: DataTypes.TEXT, allowNull: false }
|
||||
}, {
|
||||
sequelize,
|
||||
timestamps: false,
|
||||
modelName: 'Comment',
|
||||
tableName: 'comment',
|
||||
createdAt: true,
|
||||
updatedAt: true
|
||||
});
|
||||
|
||||
Comment.prototype.toJSONFor = function () {
|
||||
return {
|
||||
commentId: this.commentId,
|
||||
body: this.body
|
||||
};
|
||||
};
|
||||
|
||||
return Comment;
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
const {
|
||||
Model
|
||||
} = require('sequelize');
|
||||
module.exports = (sequelize, DataTypes) => {
|
||||
class Tag extends Model {
|
||||
/**
|
||||
* Helper method for defining associations.
|
||||
* 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({
|
||||
name: { type: DataTypes.STRING, primaryKey: true, allowNull: false }
|
||||
}, {
|
||||
sequelize,
|
||||
timestamps: false,
|
||||
modelName: 'Tag',
|
||||
tableName: 'tag',
|
||||
createdAt: true,
|
||||
updatedAt: true
|
||||
});
|
||||
|
||||
Tag.prototype.toJSONFor = function () {
|
||||
return {
|
||||
name: this.name
|
||||
};
|
||||
};
|
||||
|
||||
return Tag;
|
||||
};
|
||||
@@ -0,0 +1,65 @@
|
||||
'use strict';
|
||||
|
||||
const bcrypt = require("bcryptjs");
|
||||
|
||||
const {
|
||||
Model
|
||||
} = require('sequelize');
|
||||
module.exports = (sequelize, DataTypes) => {
|
||||
class User extends Model {
|
||||
/**
|
||||
* Helper method for defining associations.
|
||||
* This method is not a part of Sequelize lifecycle.
|
||||
* The `models/index` file will call this method automatically.
|
||||
*/
|
||||
static associate(models) {
|
||||
/* define association here */
|
||||
}
|
||||
}
|
||||
User.init({
|
||||
userId: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false},
|
||||
email: {type: DataTypes.STRING, allowNull: false, unique: true},
|
||||
username: {type: DataTypes.STRING, allowNull: false, unique: true},
|
||||
firstname: {type: DataTypes.STRING},
|
||||
lastname: {type: DataTypes.STRING},
|
||||
bio: {type: DataTypes.TEXT, allowNull: true},
|
||||
image: {type: DataTypes.TEXT, allowNull: true},
|
||||
role: {type: DataTypes.STRING},
|
||||
password: {type: DataTypes.STRING, allowNull: false}
|
||||
}, {
|
||||
sequelize,
|
||||
timestamps: false,
|
||||
modelName: 'User',
|
||||
tableName: 'user',
|
||||
createdAt: true,
|
||||
updatedAt: true
|
||||
});
|
||||
|
||||
User.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;
|
||||
});
|
||||
|
||||
User.prototype.toJSONFor = function () {
|
||||
return {
|
||||
userId: this.userId,
|
||||
email: this.email,
|
||||
username: this.username,
|
||||
firstname: this.firstname,
|
||||
lastname: this.lastname,
|
||||
bio: this.bio,
|
||||
image: this.image,
|
||||
role: this.role
|
||||
};
|
||||
};
|
||||
return User;
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
const fs = require('fs'),
|
||||
path = require('path'),
|
||||
basename = path.basename(__filename),
|
||||
chalk = require('chalk'),
|
||||
utils = require('../../routes/utils');
|
||||
|
||||
const { Sequelize } = require('sequelize');
|
||||
const db = {};
|
||||
const Op = Sequelize.Op;
|
||||
const sequelize = new Sequelize(
|
||||
process.env.MYSQL_DBNAME,
|
||||
process.env.MYSQL_DBUSER,
|
||||
process.env.MYSQL_DBPASS,
|
||||
{
|
||||
host: process.env.MYSQL_DBHOST,
|
||||
port: process.env.MYSQL_DBPORT,
|
||||
dialect: process.env.MYSQL_DBTYPE,
|
||||
$like: Op.like,
|
||||
$not: Op.not
|
||||
}
|
||||
);
|
||||
|
||||
sequelize.authenticate().then(() => {
|
||||
if (process.env.DEBUG) {
|
||||
console.log(`${utils.getDateTimeISOString()}`, chalk.green('MySQL connection has been established successfully'));
|
||||
}
|
||||
}).catch((error) => {
|
||||
console.log(`${utils.getDateTimeISOString()}`, chalk.red('Unable to connect to the MySQL database'));
|
||||
console.error(error);
|
||||
});
|
||||
|
||||
fs
|
||||
.readdirSync(__dirname)
|
||||
.filter(file => {
|
||||
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
|
||||
})
|
||||
.forEach(file => {
|
||||
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
|
||||
db[model.name] = model;
|
||||
});
|
||||
|
||||
Object.keys(db).forEach(modelName => {
|
||||
if (db[modelName].associate) {
|
||||
db[modelName].associate(db);
|
||||
}
|
||||
});
|
||||
|
||||
db.sequelize = sequelize;
|
||||
|
||||
module.exports = db;
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"env" : {
|
||||
"APP_ENV": "local",
|
||||
"NODE_ENV" : "development",
|
||||
"DEBUG": false,
|
||||
"SERVER_PORT": "3201",
|
||||
"JWT_SECRET": "$2b$10$aEsAUG7Dy8dcTORi1vaQle",
|
||||
"SESSION_LIFETIME": "3600",
|
||||
"MONGODB_URI": "mongodb://localhost:27017/adastradb",
|
||||
"SENDGRID_API_KEY": "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",
|
||||
"SENDGRID_FROM_MAIL": "contact@rampeur.fr",
|
||||
"SENDGRID_TO_MAIL": "rampeur@gmail.com",
|
||||
"AUTHORIZATION_PREFIX": "Api-Key",
|
||||
"COUCHDB_URL": "http://couchdb.unespace.com",
|
||||
"COUCHDB_DATABASE": "adastradb",
|
||||
"COUCHDB_DESIGN": "adastra_app",
|
||||
"COUCHDB_CREDENTIAL": "cmFtcGV1cjpES3hwMjRQUw==",
|
||||
"SKYDIVERID_API_URL": "https://skydiver.id/api",
|
||||
"SKYDIVERID_API_TOKEN": "xmqzgnGYMD.OJgFw1pCXCpJFGmZfSjmWK8lrpqAQNnu"
|
||||
}
|
||||
}
|
||||
Generated
+3489
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "adastra-api",
|
||||
"version": "1.0.0",
|
||||
"description": "Ad Astra API",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"author": "Solide Apps <jgautier.webdev@gmail.com>",
|
||||
"contributors": [
|
||||
"Julien Gautier <jgautier.webdev@gmail.com>"
|
||||
],
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"start": "APP_ENV=production node ./server.js",
|
||||
"dev": "APP_ENV=development node ./server.js",
|
||||
"local": "APP_ENV=local nodemon ./server.js",
|
||||
"test": "newman run ./tests/api-tests.postman.json -e ./tests/env-api-tests.postman.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^16.20.2 || ^18.19.1 || ^20.11.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sendgrid/mail": "^8.1.5",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"colors": "^1.4.0",
|
||||
"dotenv": "^16.0.3",
|
||||
"express": "^4.18.2",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"morgan": "^1.10.0",
|
||||
"mysql2": "^3.14.3",
|
||||
"nodemon": "^3.1.10",
|
||||
"sequelize": "^6.26.0",
|
||||
"slugify": "^1.6.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.0.0",
|
||||
"eslint": "^9.0.0",
|
||||
"prettier": "^2.8.0",
|
||||
"sequelize-cli": "^6.6.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
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;
|
||||
@@ -0,0 +1,23 @@
|
||||
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;
|
||||
@@ -0,0 +1,22 @@
|
||||
var router = require('express').Router();
|
||||
|
||||
router.use('/', require('./profiles'));
|
||||
router.use('/articles', require('./articles'));
|
||||
router.use('/comments', require('./comments'));
|
||||
router.use('/tags', require('./tags'));
|
||||
router.use('/profiles', require('./profiles'));
|
||||
router.use('/users', require('./users'));
|
||||
|
||||
router.use(function (err, req, res, next) {
|
||||
if (err.name === 'ValidationError') {
|
||||
return res.status(422).json({
|
||||
errors: Object.keys(err.errors).reduce(function (errors, key) {
|
||||
errors[key] = err.errors[key].message;
|
||||
return errors;
|
||||
}, {})
|
||||
});
|
||||
}
|
||||
return next(err);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,16 @@
|
||||
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;
|
||||
@@ -0,0 +1,8 @@
|
||||
const express = require("express");
|
||||
const router = express.Router();
|
||||
|
||||
const { getTags } = require("../../controllers/tags");
|
||||
|
||||
router.route("/tags/").get(getTags);
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,16 @@
|
||||
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;
|
||||
@@ -0,0 +1,4 @@
|
||||
var router = require('express').Router();
|
||||
router.use('/api', require('./api'));
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,30 @@
|
||||
const utils = {
|
||||
getDateString: () => {
|
||||
let today = new Date();
|
||||
let dateNow = today.toLocaleDateString();
|
||||
return `${dateNow}`;
|
||||
},
|
||||
getTimeString: () => {
|
||||
let today = new Date();
|
||||
let timeNow = today.toLocaleTimeString();
|
||||
return `${timeNow}`;
|
||||
},
|
||||
getDateTimeString: (delimiter = true) => {
|
||||
let today = new Date();
|
||||
let dateString = `${today.toLocaleDateString()} ${today.toLocaleTimeString()}`;
|
||||
if (delimiter) {
|
||||
dateString = `[${dateString}]`;
|
||||
}
|
||||
return dateString;
|
||||
},
|
||||
getDateTimeISOString: (delimiter = true) => {
|
||||
let today = new Date();
|
||||
let dateString = today.toISOString();
|
||||
if (delimiter) {
|
||||
dateString = `[${dateString}]`;
|
||||
}
|
||||
return dateString;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = utils;
|
||||
@@ -0,0 +1,132 @@
|
||||
var appEnv = process.env.APP_ENV;
|
||||
if (appEnv == undefined) {
|
||||
appEnv = 'development';
|
||||
}
|
||||
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");
|
||||
|
||||
var isProduction = appEnv === 'production';
|
||||
|
||||
const app = express();
|
||||
|
||||
// Body parser
|
||||
app.use(express.json());
|
||||
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
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("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();
|
||||
});
|
||||
|
||||
/*
|
||||
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");
|
||||
|
||||
// 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" });
|
||||
Comment.belongsTo(User, { as: "author", foreignKey: "authorId" });
|
||||
Article.hasMany(Comment, { foreignKey: "articleId", onDelete: "CASCADE" });
|
||||
Comment.belongsTo(Article, { foreignKey: "articleId" });
|
||||
User.belongsToMany(Article, { as: "favorites", through: "Favorites", timestamps: false });
|
||||
Article.belongsToMany(User, { through: "Favorites", foreignKey: "articleId", timestamps: false });
|
||||
Article.belongsToMany(Tag, { through: "TagLists", as: "tagLists", foreignKey: "articleId", timestamps: false, onDelete: "CASCADE" });
|
||||
Tag.belongsToMany(Article, { through: "ArticleTags", uniqueKey: false, timestamps: false });
|
||||
|
||||
|
||||
// Route files
|
||||
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);
|
||||
app.use(profiles);
|
||||
app.use(articles);
|
||||
app.use(comments);
|
||||
app.use(tags);
|
||||
|
||||
//app.use(require('./routes'));
|
||||
|
||||
app.use(errorHandler);
|
||||
//console.log(`User: ${User}`);
|
||||
|
||||
//Article.sync();
|
||||
/*
|
||||
const sync = async () => await sequelize.sync({ force: true });
|
||||
sync().then(() => {
|
||||
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}`));
|
||||
}
|
||||
|
||||
// finally, let's start our server...
|
||||
startServer();
|
||||
@@ -0,0 +1,28 @@
|
||||
const { Sequelize } = require('sequelize');
|
||||
|
||||
const Op = Sequelize.Op;
|
||||
const sequelize = new Sequelize(
|
||||
process.env.MYSQL_DBNAME,
|
||||
process.env.MYSQL_DBUSER,
|
||||
process.env.MYSQL_DBPASS,
|
||||
{
|
||||
host: process.env.MYSQL_DBHOST,
|
||||
port: process.env.MYSQL_DBPORT,
|
||||
dialect: process.env.MYSQL_DBTYPE,
|
||||
$like: Op.like,
|
||||
$not: Op.not
|
||||
}
|
||||
);
|
||||
|
||||
const checkConnection = async () => {
|
||||
try {
|
||||
await sequelize.authenticate();
|
||||
console.log(`DB Connected`.cyan.underline.bold);
|
||||
} catch (error) {
|
||||
console.error("Unable to connect to the database:".red.bold, error);
|
||||
}
|
||||
};
|
||||
|
||||
checkConnection();
|
||||
|
||||
module.exports = sequelize;
|
||||
@@ -0,0 +1,8 @@
|
||||
class ErrorResponse extends Error {
|
||||
constructor(message, statusCode) {
|
||||
super(message);
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ErrorResponse;
|
||||
@@ -0,0 +1,38 @@
|
||||
const appendTagList = (articleTags, article) => {
|
||||
const tagList = articleTags.map((tag) => tag.name);
|
||||
|
||||
if (!article) return tagList;
|
||||
delete article.dataValues.tagLists;
|
||||
article.dataValues.tagList = tagList;
|
||||
};
|
||||
|
||||
const appendFavorites = async (loggedUser, article) => {
|
||||
const favorited = await article.hasUser(loggedUser ? loggedUser : null);
|
||||
article.dataValues.favorited = loggedUser ? favorited : false;
|
||||
|
||||
const favoritesCount = await article.countUsers();
|
||||
article.dataValues.favoritesCount = favoritesCount;
|
||||
};
|
||||
|
||||
const appendFollowers = async (loggedUser, toAppend) => {
|
||||
//
|
||||
if (toAppend?.author) {
|
||||
const author = await toAppend.getAuthor();
|
||||
const following = await author.hasFollower(loggedUser ? loggedUser : null);
|
||||
toAppend.author.dataValues.following = loggedUser ? following : false;
|
||||
|
||||
const followersCount = await author.countFollowers();
|
||||
toAppend.author.dataValues.followersCount = followersCount;
|
||||
//
|
||||
} else {
|
||||
const following = await toAppend.hasFollower(
|
||||
loggedUser ? loggedUser : null
|
||||
);
|
||||
toAppend.dataValues.following = loggedUser ? following : false;
|
||||
|
||||
const followersCount = await toAppend.countFollowers();
|
||||
toAppend.dataValues.followersCount = followersCount;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { appendTagList, appendFavorites, appendFollowers };
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
const jwt = require("jsonwebtoken");
|
||||
|
||||
module.exports.sign = async (user) => {
|
||||
const token = await jwt.sign(
|
||||
{ userId: user.userId, username: user.username, email: user.email },
|
||||
process.env.JWT_SECRET
|
||||
);
|
||||
return token;
|
||||
};
|
||||
|
||||
module.exports.verify = async (token) => {
|
||||
const decoded = await jwt.verify(token, process.env.JWT_SECRET);
|
||||
return decoded;
|
||||
};
|
||||
Reference in New Issue
Block a user