Skip to content

Commit

Permalink
[finishes #162171014] Document all API using swagger
Browse files Browse the repository at this point in the history
  • Loading branch information
el-Joft committed Jan 8, 2019
2 parents 55f517b + 510cccf commit d61f199
Show file tree
Hide file tree
Showing 31 changed files with 3,581 additions and 2,664 deletions.
202 changes: 194 additions & 8 deletions controllers/ArticlesController.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import {
checkUser,
checkTitle,
createNewTags,
calcReadingTime
calcReadingTime,
userIsOnwerOrAdmin,
checkUserRole
} from '../helpers/articleHelper';
import ReadingStatsModelQuery from '../lib/ReadingStatsModelQuery';
import eventEmitter from '../helpers/eventEmitter';
Expand Down Expand Up @@ -69,8 +71,13 @@ class ArticlesController {
const {
size = 20, order = 'ASC', orderBy = 'id', offset = 0
} = req.query;

try {
const articles = await Article.findAndCountAll({
where: {
isPublished: true,
isArchived: false
},
include: [
{
model: Tag,
Expand Down Expand Up @@ -102,6 +109,101 @@ class ArticlesController {
}
}

/**
* @description - list archived articles
* @param {object} req
* @param {object} res
* @returns {object} Returned object
*/
static async getArchived(req, res) {
const {
size = 20, order = 'ASC', orderBy = 'id', offset = 0
} = req.query;

try {
const articles = await Article.findAndCountAll({
where: {
isArchived: true
},
include: [
{
model: Tag,
as: 'tags',
attributes: ['tagName'],
through: {
attributes: []
}
}
],
limit: size,
offset,
order: [[orderBy, order]]
});
if (articles.rows.length === 0) {
return StatusResponse.success(res, {
message: 'No article found'
});
}
return StatusResponse.success(res, {
message: 'List of archived articles',
articles,
...pagination(articles, offset, size)
});
} catch (error) {
return StatusResponse.internalServerError(res, {
message: `something went wrong, please try again.... ${error}`
});
}
}

/**
* @description - list unpublished articles
* @param {object} req
* @param {object} res
* @returns {object} Returned object
*/
static async getUnpublished(req, res) {
const {
size = 20, order = 'ASC', orderBy = 'id', offset = 0
} = req.query;

try {
const articles = await Article.findAndCountAll({
where: {
isPublished: false,
isArchived: false,
},
include: [
{
model: Tag,
as: 'tags',
attributes: ['tagName'],
through: {
attributes: []
}
}
],
limit: size,
offset,
order: [[orderBy, order]]
});
if (articles.rows.length === 0) {
return StatusResponse.success(res, {
message: 'No article found'
});
}
return StatusResponse.success(res, {
message: 'List of unpublished articles',
articles,
...pagination(articles, offset, size)
});
} catch (error) {
return StatusResponse.internalServerError(res, {
message: `something went wrong, please try again.... ${error}`
});
}
}

/**
* @description - fetch single article
* @param {object} req
Expand All @@ -110,10 +212,14 @@ class ArticlesController {
*/
static async get(req, res) {
const whereFilter = checkIdentifier(req.params.identifier);
const { userId, roleId } = req.app.locals.user;

try {
const fetchArticle = await Article.findOne({
where: { ...whereFilter },
where: {
...whereFilter,
...checkUserRole(roleId, userId)
},
include: [
{
model: Tag,
Expand All @@ -129,14 +235,33 @@ class ArticlesController {
}
]
});
if (req.app.locals.user) {
const { userId } = req.app.locals.user;
if (!fetchArticle) {
return StatusResponse.notfound(res, {
message: 'Could not find article'
});
}

if (userId) {
const readInfo = {
articleId: fetchArticle.id,
userId
};
await ReadingStatsModelQuery.createReaderStats(readInfo);
}
if ((fetchArticle.userId === userId)
|| (roleId === 3 || (userId && fetchArticle.isPublished))) {
return StatusResponse.success(res, {
message: 'success',
article: fetchArticle
});
}

if (roleId !== 1 && (userId && !fetchArticle.isPublished)) {
return StatusResponse.notfound(res, {
message: 'Could not find article'
});
}

return StatusResponse.success(res, {
message: 'success',
article: fetchArticle
Expand Down Expand Up @@ -213,23 +338,84 @@ class ArticlesController {
*/
static async archive(req, res) {
const { articles } = models;
const { userId } = req.app.locals.user;
const { userId, roleId } = req.app.locals.user;
const whereFilter = checkIdentifier(req.params.identifier);
try {
const article = await ArticleQueryModel.getArticleByIdentifier(whereFilter);
if (!checkUser(article, userId)) {

if (!userIsOnwerOrAdmin(article, userId, roleId)) {
return StatusResponse.forbidden(res, {
message: 'Request denied'
});
}
const data = { isArchived: true };
await articles.update(data, {
const archivedArticle = await articles.update(data, {
where: { ...whereFilter },
returning: true,
plain: true
});
const payload = roleId === 1
? {
message: 'Article deleted(archived) successfully',
article: archivedArticle[1]
}
: {
message: 'Article deleted(archived) successfully'
};
return StatusResponse.success(res, payload);
} catch (error) {
return StatusResponse.internalServerError(res, {
message: `something went wrong, please try again.... ${error}`
});
}
}

/**
* @description - publish article
* @param {object} req
* @param {object} res
* @returns {object} Returned object
*/
static async publish(req, res) {
const { articles } = models;
const whereFilter = checkIdentifier(req.params.identifier);
try {
const data = { isPublished: true };
const article = await articles.update(data, {
where: { ...whereFilter },
returning: true,
plain: true
});
return StatusResponse.success(res, {
message: 'Article published successfully!',
article: article[1]
});
} catch (error) {
return StatusResponse.internalServerError(res, {
message: `something went wrong, please try again.... ${error}`
});
}
}

/**
* @description - publish article
* @param {object} req
* @param {object} res
* @returns {object} Returned object
*/
static async unpublish(req, res) {
const { articles } = models;
const whereFilter = checkIdentifier(req.params.identifier);
try {
const data = { isPublished: false };
const article = await articles.update(data, {
where: { ...whereFilter },
returning: true,
plain: true
});
return StatusResponse.success(res, {
message: 'Article deleted(archived) successfully'
message: 'Article unpublished successfully!',
article: article[1]
});
} catch (error) {
return StatusResponse.internalServerError(res, {
Expand Down
2 changes: 1 addition & 1 deletion controllers/AuthController.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class AuthController {

mailer.sendVerificationMail(email, username, link);

const { id: roleId } = await roles.find({ where: { name: 'user' } });
const { id: roleId } = await roles.find({ where: { name: 'author' } });
const newUser = await users.create(
{
email,
Expand Down
23 changes: 18 additions & 5 deletions controllers/CommentHistoriesController.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import models from '../models';
import StatusResponse from '../helpers/StatusResponse';
import { checkUser } from '../helpers/articleHelper';
import { getArticleWhereClause, getCommentWhereClause } from '../helpers/commentHelper';

const { comments, articles } = models;

Expand Down Expand Up @@ -60,7 +61,7 @@ class CommentHistoriesController {
limit: 1
});


updatedComment[1].commentId = undefined;
await comments.create(latestComment.dataValues);

return StatusResponse.success(res, {
Expand All @@ -82,15 +83,27 @@ class CommentHistoriesController {
*/
static async getACommentHistory(req, res) {
const { articleId, commentId } = req.params;
const { userId, roleId } = req.app.locals.user;

try {
const article = await articles.findOne({ where: { id: articleId } });
if (!article) {
return StatusResponse.notfound(res, {
message: 'Article Not Found'
});
}
const comment = await comments.findOne({ where: { commentId: null, id: commentId } });
if (!comment) {
return StatusResponse.notfound(res, {
message: 'Comment Not Found'
});
}
const commentHistory = await comments.findAll({
where: { articleId, commentId, isArchived: false },
where: { articleId, commentId, ...getCommentWhereClause(article, comment, roleId, userId) },
order: [['id', 'DESC']],
include: [{
model: articles,
where: {
isArchived: false
},
where: getArticleWhereClause(article, roleId, userId),
attributes: []
}],
});
Expand Down
4 changes: 2 additions & 2 deletions controllers/FollowersController.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ class FollowersController {
return StatusResponse.notfound(res, payload);
}
const payload = {
message: allReturnedFollowers
data: allReturnedFollowers
};
return StatusResponse.success(res, payload);
} catch (error) {
Expand Down Expand Up @@ -126,7 +126,7 @@ class FollowersController {
return StatusResponse.success(res, payload);
}
return res.status(200).send({
message: following
data: following
});
} catch (error) {
return StatusResponse.internalServerError(res, {
Expand Down
5 changes: 4 additions & 1 deletion controllers/RolesController.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import models from '../models';
import StatusResponse from '../helpers/StatusResponse';
// import pagination from '../helpers/pagination';

const { users, profiles, roles } = models;
const {
users, profiles, roles,
} = models;

/**
* @description RolesController class
Expand Down
22 changes: 21 additions & 1 deletion helpers/articleHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ const checkTitle = (title, articleTitle) => {

const checkUser = (article, userId) => article.userId === userId;

const userIsOnwerOrAdmin = (article, userId, roleId) => roleId === 1 || article.userId === userId;

/**
* @description This method is used to create new tags abd return the created tag ids
* @param {Array} tags - An array of tags <= 5
Expand Down Expand Up @@ -43,6 +45,24 @@ const calcReadingTime = (bodyText) => {
return readingTime > 1 ? `${readingTime} mins read` : `${readingTime} min read`;
};

const isPublished = article => article.isPublished;

const checkUserRole = (roleId, userId) => {
let where = { isArchived: false };

if (roleId === 1) {
where = {};
}
if (!userId) {
where = {
isArchived: false,
isPublished: true
};
}
return where;
};

export {
checkIdentifier, checkUser, checkTitle, createNewTags, calcReadingTime
checkIdentifier, checkUser, checkTitle, createNewTags, calcReadingTime, isPublished,
userIsOnwerOrAdmin, checkUserRole
};
Loading

0 comments on commit d61f199

Please sign in to comment.