Skip to content

Commit

Permalink
Merge 24afc95 into 840a9bc
Browse files Browse the repository at this point in the history
  • Loading branch information
klevamane committed Sep 5, 2018
2 parents 840a9bc + 24afc95 commit 302c25d
Show file tree
Hide file tree
Showing 13 changed files with 253 additions and 54 deletions.
12 changes: 11 additions & 1 deletion .babelrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
{
"presets": ["env"]
"presets": [
["env", {
"targets": {
"node": "current"
}
}]
],
"plugins": [
"transform-runtime",
"transform-async-to-generator"
]
}
8 changes: 7 additions & 1 deletion config/config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { } from 'dotenv/config';

module.exports = {
development: {
username: process.env.DB_USER,
Expand All @@ -13,14 +15,18 @@ module.exports = {
database: process.env.TEST_DB_DATABASE,
host: process.env.TEST_DB_HOST,
dialect: 'postgres',
operatorsAliases: false
operatorsAliases: false,

},
production: {
username: process.env.PROD_DB_USER,
password: process.env.PROD_DB_PASSWORD,
database: process.env.PROD_DB_DATABASE,
host: process.env.PROD_DB_HOST,
dialect: 'postgres',
dialectOptions: {
ssl: true
},
operatorsAliases: false
}
};
6 changes: 2 additions & 4 deletions controllers/ArticleController.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,12 @@ class ArticleController {
static listAllArticles(req, res, next) {
const { page, limit } = req;
let offset = null;
if (req.query.author || req.query.tag || req.query.title) return next();

if (page || limit) {
// calculate offset
offset = limit * (page - 1);
}

return Article
.findAll({
include: [{
Expand Down Expand Up @@ -171,9 +171,7 @@ class ArticleController {
*/
static deleteArticle(req, res, next) {
const { slug } = req.params;
Article.destroy({
where: { slug }
})
Article.destroy({ where: { slug } })
.then(() => res.status(200).json({ message: 'Article successfully deleted' }))
.catch(next);
}
Expand Down
2 changes: 1 addition & 1 deletion controllers/UsersController.js
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ export default class UsersController {
static async verifyEmail(req, res) {
const { token } = req.params;
try {
const decodedUserData = jwt.verify(token, process.env.SECRETE_KEY);
const decodedUserData = jwt.verify(token, process.env.SECRET_KEY);
const userFound = await User.findOne({ where: { id: decodedUserData.id } });
if (userFound) {
if (userFound.isverified) {
Expand Down
61 changes: 61 additions & 0 deletions helpers/exports.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import Sequelize from 'sequelize';
import { trim, escape } from 'validator';
import { User } from '../models';
import sendVerificationEmail from './sendmail';

const { Op } = Sequelize;

exports.resendVerificationEmail = async (req, res) => {
const { email } = req.body.user;
try {
Expand Down Expand Up @@ -35,3 +39,60 @@ exports.resendVerificationEmail = async (req, res) => {

}
};

/**
* @function searchByTagAuthorOrTitle
* @summary Articles can be searched by Tag, Author or TItle
* @param {object} req - Request object
* @param {object} res - Response object
* @returns {object} returns the list of articles matching the search criteria
*/
exports.searchByTagAuthorOrTitle = (req, res) => {
const searchParameters = {};
// Get every parameter and key passed in the query string
const keysAndValues = Object.entries(req.query);
let { pageNumber = 1, pageSize = 10 } = req.query;
pageNumber = parseInt(pageNumber, 10);
pageSize = parseInt(pageSize, 10);
if ((pageNumber < 1 || !Number.isInteger(pageNumber)) || pageSize < 10) {
return res.status(400).json({
errors: {
body: [
'Please ensure your query is an integer and pageSize is greater than 9'
]
}
});
}
const limit = pageSize;
const offset = (pageNumber - 1) * limit;
const queryStringValues = Object.values(req.query);
let textToSearch = queryStringValues[0];
textToSearch = trim(escape(textToSearch));

// selects the search value from the key
const searchCriteria = keysAndValues[0][0];
if (searchCriteria === 'tag') {
searchParameters.where = {
[Op.or]: [{ tagList: { [Op.contains]: [textToSearch] } }]
};
}
if (searchCriteria === 'title') {
searchParameters.where = {
title: { [Op.iLike]: `%${textToSearch}%` }
};
}
/**
* set the relationship to search from the right table
* since the attribute to be searched for is on the right table
* */
if (searchCriteria === 'author') {
searchParameters.where = { username: Sequelize.where(Sequelize.col('User.username'), { [Op.eq]: `${textToSearch}` }) };
}
searchParameters.limit = limit;
searchParameters.offset = offset;
searchParameters.include = [{
model: User,
attributes: ['username'],
}];
return searchParameters;
};
2 changes: 1 addition & 1 deletion helpers/sendmail.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import jwt from 'jsonwebtoken';
import winston from 'winston';
import mailtemplate from './mailtemplate';

exports.sendEmail = async (userToBeVerified) => {
exports.sendEmail = (userToBeVerified) => {
const token = jwt.sign(
{ id: userToBeVerified.id },
process.env.SECRET_KEY, { expiresIn: 60 * process.env.VERIFYTOKEN_EXPIRY }
Expand Down
19 changes: 12 additions & 7 deletions helpers/utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import mailer from 'nodemailer';
import stubTransport from 'nodemailer-stub-transport';
import { User } from '../models';


/**
* Class representing all utility functions
*
Expand Down Expand Up @@ -143,12 +142,18 @@ export default class Utilities {

/**
* @function increaseCount
* @summary: A funtion to increase count
* each time an article is updated
* @param {Integer} count: input param
* @returns {Integer} number of count: for updating articles
* @summary: API controller to handle requests
* to delete an article
* @param {Integer} num: input param
* @returns {object} api response: article object for
* successful requests, or error object for
* requests that fail
*/
static increaseCount(count) {
if (Number.isInteger(count)) return count + 1;
static increaseCount(num) {
if (Number.isInteger(num)) {
let updateCount = num;
updateCount += 1;
return updateCount;
}
}
}
26 changes: 26 additions & 0 deletions middlewares/searchArticles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import models from '../models';
import { searchByTagAuthorOrTitle } from '../helpers/exports';

const { Article } = models;
/**
* @function searchForArticle
* @summary Return a user's profile after updating it
* @param {object} req - Request object
* @param {object} res - Response object
* @param {objecg} next - passes error to the error handler
* @returns {object} An object containing all the data related to the user if update successful
*/
const searchForArticles = async (req, res, next) => {
try {
// query the database
const searchParameters = searchByTagAuthorOrTitle(req, res);
const articles = await Article.findAll(searchParameters);
if (articles.length > 0) {
return res.status(200).send({ articles, message: 'These are the articles found' });
}
return res.status(200).json({ message: 'No article found for your search' });
} catch (err) {
next(err);
}
};
export default searchForArticles;
47 changes: 29 additions & 18 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,15 @@
"slugify": "^1.3.0",
"underscore": "^1.9.1",
"validatorjs": "^3.14.2",
"validator": "^10.5.0",
"winston": "^3.0.0"
},
"devDependencies": {
"@types/dotenv": "^4.0.3",
"babel-cli": "^6.26.0",
"babel-istanbul": "^0.12.2",
"babel-plugin-transform-async-to-generator": "^6.24.1",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",
"eslint": "^5.2.0",
"eslint-config-airbnb": "^17.0.0",
Expand Down
5 changes: 2 additions & 3 deletions routes/api/articleRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import ParamsValidator from '../../middlewares/ParamsValidator';
import idIsInteger from '../../middlewares/idIsInteger';
import checkArticle from '../../middlewares/checkArticle';
import { checkCount, articleExists } from '../../middlewares/checkUser';

import searchForArticles from '../../middlewares/searchArticles';

const router = Router();

Expand All @@ -20,9 +20,8 @@ router.delete('/articles/:slug', verifyToken, articleExists, ArticleControllers.

router.get('/articles/:slug', ArticleControllers.getArticle);

router.get('/articles', ParamsValidator.validatePageQuery, ArticleControllers.listAllArticles);
router.get('/articles', ArticleControllers.listAllArticles);
router.post('/articles/:slug/like', verifyToken, ArticleControllers.likeArticle);
router.get('/articles', ParamsValidator.validatePageQuery, ArticleControllers.listAllArticles, searchForArticles);

router.put('/articles/:id/like', verifyToken, idIsInteger, checkArticle, ArticleControllers.likeArticle);

Expand Down
Loading

0 comments on commit 302c25d

Please sign in to comment.