Skip to content

Commit

Permalink
Merge ab00cad into 00079fd
Browse files Browse the repository at this point in the history
  • Loading branch information
azupatrick0 committed Dec 18, 2018
2 parents 00079fd + ab00cad commit 3bff82c
Show file tree
Hide file tree
Showing 6 changed files with 120 additions and 62 deletions.
24 changes: 9 additions & 15 deletions controllers/ArticlesController.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ class ArticlesController {
*/
static async list(req, res) {
const {
size, page = 1, order = 'ASC', orderBy = 'id'
size = 20, order = 'ASC', orderBy = 'id', offset = 0
} = req.query;
try {
const articles = await Article.findAndCountAll({
Expand All @@ -80,27 +80,21 @@ class ArticlesController {
order: [[orderBy, order]]
});

const {
limit, offset, totalPages, currentPage
} = pagination(page, size, articles.count);
const fetchedArticles = articles.rows.slice(offset, parseInt(offset, 10)
+ parseInt(limit, 10));
// const {
// limit, offset, totalPages, currentPage
// } = pagination(page, size, articles.count);
// const fetchedArticles = articles.rows.slice(offset, parseInt(offset, 10)
// + parseInt(limit, 10));

if (fetchedArticles.length === 0) {
if (articles.length === 0) {
return StatusResponse.success(res, {
message: 'No article found'
});
}
return StatusResponse.success(res, {
message: 'List of articles',
articles: fetchedArticles,
metadata: {
count: articles.count,
currentPage,
articleCount: fetchedArticles.length,
limit,
totalPages
}
articles,
...pagination(articles, offset, size)
});
} catch (error) {
return StatusResponse.internalServerError(res, {
Expand Down
109 changes: 86 additions & 23 deletions controllers/SearchArticlesController.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import Sequelize from 'sequelize';
import model from '../models';
import StatusResponse from '../helpers/StatusResponse';
import pagination from '../helpers/pagination';

const {
articles,
ArticleTag,
tags,
users,
profiles
} = model;

/**
Expand All @@ -14,6 +18,49 @@ const {
* @returns {class} Articles searched for
*/
class SearchArticlesController {
// static async search(req, res) {
// const {
// size, offset, order, orderBy, author, title, tag
// } = req.query;
// const whereQuery = {};
// // if (author) {
// // whereQuery.author = `%${author}%`
// // }
// if (title) {
// whereQuery.title = `%${title}%`;
// }
// // if (tag) {
// // if (Array.isArray(tag)) {
// // whereQuery.tags = tag.map((cur) => `%${cur}%`);
// // } else {
// // whereQuery.tags = tag.split(',').map((cur) => `%${cur}%`);
// // }
// // }

// console.log(whereQuery)

// try {
// const foundArticles = await articles.findAndCountAll({
// where: {
// title
// },
// offset,
// limit: size,
// order: [[orderBy, order]]
// });

// return StatusResponse.success(res, { msg: 'success' });
// } catch (error) {
// return StatusResponse.internalServerError(res, {
// message: 'An error occured, Articles not returned succesfully, please try again',
// error: {
// body: [`Internal server error => ${error}`]
// }
// });
// }
// }


/**
* @description - This method takes care of retrieving articles by authors
* @param {object} req
Expand All @@ -22,32 +69,40 @@ class SearchArticlesController {
*/
static async byAuthor(req, res) {
const {
size, page = 1, order = 'DESC', orderBy = 'id'
size = 20, order = 'DESC', orderBy = 'id', offset = 0
} = req.query;
try {
const articlesByAuthor = await articles.findAndCountAll({
where: {
userId: req.app.locals.user.userId,
userId: {
[Sequelize.Op.or]: req.app.locals.user.userIds
}
},
attributes: { exclude: ['userId'] },
include: {
model: users,
attributes: { exclude: ['email', 'password', 'emailVerification', 'resettingPassword', 'createdAt', 'updatedAt', 'roleId'], },
include: {
model: profiles,
attributes: { exclude: ['id', 'firstName', 'lastName', 'biodata', 'image', 'location', 'twitterUsername', 'facebookUsername', 'createdAt', 'updatedAt', 'userId'] },
},
},
// include: [{
// model: users,
// },
// {
// model: profiles,
// }],
// attributes: { exclude: ['user'] },
offset,
limit: size,
order: [[orderBy, order]]
});
const {
limit, offset, totalPages, currentPage
} = pagination(page, size, articlesByAuthor.count);
const fetchedArticles = articlesByAuthor.rows.slice(offset, parseInt(offset, 10)
+ parseInt(limit, 10));

if (fetchedArticles.length >= 1) {
if (articlesByAuthor.count >= 1) {
StatusResponse.success(res, {
message: 'All Articles by this author returned succesfully',
articles: fetchedArticles,
metadata: {
count: articlesByAuthor.count,
currentPage,
articleCount: fetchedArticles.length,
limit,
totalPages
}
message: 'All Articles returned succesfully',
articles: articlesByAuthor,
...pagination(articlesByAuthor, offset, size),
});
} else {
StatusResponse.notfound(res, {
Expand All @@ -72,10 +127,11 @@ class SearchArticlesController {
* @returns {object} Articles by title
*/
static async byTitle(req, res) {
// const searchSplitTitles = req.query.title.split('').map(eachString => `%${eachString}%`);
try {
const articlesByTitle = await articles.findAndCountAll({
where: {
title: req.query.title,
title: { $ilike: `%${req.query.title}%` }
}
});
if (articlesByTitle.count >= 1) {
Expand Down Expand Up @@ -109,11 +165,18 @@ class SearchArticlesController {
try {
const articlesByTags = await ArticleTag.findAndCountAll({
where: {
tagId: req.app.locals.tag.tagId
},
include: {
model: articles,
tagId: {
[Sequelize.Op.or]: req.app.locals.tag.tagIds
}
},
include: [
{
model: articles
},
{
model: tags
}
],
attributes: { exclude: ['createdAt', 'updatedAt', 'tagId', 'articleId'] }
});
if (articlesByTags.count >= 1) {
Expand Down
22 changes: 8 additions & 14 deletions helpers/pagination.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
const pagination = (page, size, count) => {
let currentPage = Math.abs(Number(page)) || 1;
let offset = 0;
let limit = 20;
const sizeNo = Number(size);
if (!Number.isNaN(sizeNo) && sizeNo > 0) limit = size;
const totalPages = Math.ceil(count / limit);
if (currentPage > totalPages) currentPage = 1;
offset = (currentPage - 1) * limit;
if (Number.isNaN(offset)) offset = 10;
return {
limit, offset, currentPage, totalPages
};
};
const pagination = (data, offset, size) => ({
metadata: {
count: data.count,
currentPage: Math.floor(offset / size) + 1,
pageSize: data.rows.length,
totalPages: Math.ceil(data.count / size)
}
});

export default pagination;
9 changes: 5 additions & 4 deletions middlewares/ProfilesMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,18 +38,19 @@ const validProfileInput = (req, res, next) => {

// This function checks to see whether a profile exist or not [used in filtering articles by author]
const getAuthor = async (req, res, next) => {
const author = await profiles.findOne({
const author = await profiles.findAndCountAll({
where: {
username: req.query.author
username: { $ilike: `%${req.query.author}%` }
},
});
if (!author) {
if (author.count < 1) {
return StatusResponse.notfound(res, {
message: 'No such author',
});
}
const userIds = author.rows.map(val => val.id);
req.app.locals.user = {
userId: author.userId,
userIds,
};
return next();
};
Expand Down
12 changes: 9 additions & 3 deletions middlewares/articleMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,19 +49,25 @@ const checkTags = (req, res, next) => {
const { tags } = models;

const getTagId = async (req, res, next) => {
let validTags;
if (Array.isArray(req.query.tag)) {
validTags = req.query.tag.map(tag => tag.replace(/ /g, ''));
} else {
validTags = [req.query.tag].map(tag => tag.replace(/ /g, ''));
}
const tag = await tags.findAndCountAll({
where: {
tagName: req.query.tag
tagName: { $ilike: { $any: `{%${validTags}%}` } }
},
});
if (tag.count < 1) {
return StatusResponse.notfound(res, {
message: 'No Articles with such tags',
});
}
req.tagId = tag.rows[0].id;
const tagIds = tag.rows.map(val => val.id);
req.app.locals.tag = {
tagId: req.tagId,
tagIds,
};
return next();
};
Expand Down
6 changes: 3 additions & 3 deletions test/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ describe('Heimdal Search and Filter Test Suite', () => {
res.body.should.be.a('object');
res.body.should.have.property('message');
res.body.should.have.property('articles');
res.body.message.should.equal('All Articles by this author returned succesfully');
res.body.message.should.equal('All Articles returned succesfully');
});

it('should return status code 404 on not finding an author', async () => {
const res = await chai.request(app)
.get('/api/v1/articles_search/author?author=johnjdbsjsibbwojbwdbwid8383e3939e3iw39i###$@!@#@@#@#');
.get('/api/v1/articles_search/author?author=1234545');
res.status.should.equal(404);
res.body.should.be.a('object');
res.body.should.have.property('message');
Expand Down Expand Up @@ -72,7 +72,7 @@ describe('Heimdal Search and Filter Test Suite', () => {

it('should return status code 404 if articles do not exist that have such tags ', async () => {
const res = await chai.request(app)
.get('/api/v1/articles_search/tag?tag=nosuchtags');
.get('/api/v1/articles_search/tag?tag=§zxj');
res.status.should.equal(404);
res.body.should.be.a('object');
res.body.should.have.property('message');
Expand Down

0 comments on commit 3bff82c

Please sign in to comment.