Skip to content

Commit

Permalink
Merge pull request #36 from andela/ch-errors-helper-update-#166800381
Browse files Browse the repository at this point in the history
#166800381 Ensure the error objects respect the structure provided in the README
  • Loading branch information
MemunaHaruna committed Jun 20, 2019
2 parents 4a90c32 + edeb2fe commit 8cb6b27
Show file tree
Hide file tree
Showing 15 changed files with 146 additions and 121 deletions.
69 changes: 0 additions & 69 deletions .eslintrc.js

This file was deleted.

90 changes: 90 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
{
"root": true,
"extends": "airbnb-base",
"env": {
"node": true,
"es6": true,
"mocha": true
},
"rules": {
"one-var": 0,
"one-var-declaration-per-line": 0,
"new-cap": [
2,
{
"newIsCap": true,
"capIsNew": true,
"properties": true
}
],
"consistent-return": 0,
"no-param-reassign": 0,
"comma-dangle": 0,
"curly": ["error", "multi-line"],
"import/no-unresolved": [
2,
{
"commonjs": true
}
],
"no-shadow": [
"error",
{
"allow": ["req", "res", "err"]
}
],
"valid-jsdoc": [
"error",
{
"requireReturn": true,
"requireReturnType": true,
"requireParamDescription": false,
"requireReturnDescription": true
}
],
"require-jsdoc": [
"error",
{
"require": {
"FunctionDeclaration": true,
"MethodDefinition": true,
"ClassDeclaration": true
}
}
],
"no-extra-parens": [
"error",
"all",
{
"conditionalAssign": false
}
],
"no-irregular-whitespace": "error",
"no-unexpected-multiline": "error",
"no-unreachable": "error",
"use-isnan": "error",
"block-scoped-var": "error",
"dot-notation": "error",
"eqeqeq": ["error", "always"],
"no-else-return": "error",
"no-extra-bind": "error",
"no-invalid-this": "error",
"no-magic-numbers": [
"error",
{
"ignore": [1],
"ignoreArrayIndexes": true
}
],
"no-self-assign": "error",
"wrap-iife": ["error", "outside"],
"no-use-before-define": [
"error",
{
"functions": true,
"classes": true
}
],
"function-paren-newline": ["error", "never"]
}
}
10 changes: 4 additions & 6 deletions src/api/controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import generateToken from '../../helpers/tokens/generate.token';
import sendResult from '../../helpers/results/send.auth';
import status from '../../helpers/constants/status.codes';
import environments from '../../configs/environments';
import sendError from '../../helpers/error.sender';
import errors from '../../helpers/constants/error.messages';

const { User } = models;
const env = environments.currentEnv;
Expand Down Expand Up @@ -56,13 +58,9 @@ export default class Auth {
const token = generateToken(tokenData, env.secret);
return sendResult(res, status.OK, 'user logged in successfully', user, token);
}
return res.status(status.UNAUTHORIZED).json({
message: 'password is incorrect'
});
return sendError(status.UNAUTHORIZED, res, 'password', errors.incorectPassword);
}
return res.status(status.NOT_FOUND).json({
message: "user doesn't exist"
});
return sendError(status.NOT_FOUND, res, 'email', errors.unkownEmail);
});
}
}
16 changes: 7 additions & 9 deletions src/api/controllers/password.reset.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,16 +59,14 @@ export default class PasswordReset {
const salt = genSaltSync(parseFloat(env.hashRounds));
const hashedPassword = hashSync(userPassword, salt);

await User.update(
{
password: hashedPassword
},
{
where: {
email: userEmail
}
await User.update({
password: hashedPassword
},
{
where: {
email: userEmail
}
);
});

// Sending the result
result.status = status.OK;
Expand Down
1 change: 0 additions & 1 deletion src/api/routes/docs.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import swaggerDocument from '../../docs/swagger.json';

const v2Docs = express();


// Swagger documentation
v2Docs.use('/', swaggerUI.serve);
v2Docs.get('/', swaggerUI.setup(swaggerDocument));
Expand Down
12 changes: 4 additions & 8 deletions src/api/routes/password.reset.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,17 @@ import validateUpdatePassword from '../../middlewares/validations/validate.updat

const router = new Router();

router.post(
'/',
router.post('/',
verifyBody,
validateInputs(true, 'resetPassword', ['email']),
validateResetEmail,
resetController.sendRecoveryEmail
);
resetController.sendRecoveryEmail);

router.post(
'/update/:email',
router.post('/update/:email',
verifyBody,
validateInputs(true, 'updatePassword', ['password']),
validateUpdatePassword,
resetController.updatePassword
);
resetController.updatePassword);

router.get('/:token', validateResetLink, resetController.verifyRecoveryLink);

Expand Down
6 changes: 5 additions & 1 deletion src/helpers/constants/error.messages.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
export default {
email: 'Please provide a valid email',
defaultError: 'Invalid request data. Try again',
password: 'Invalid password provided'
password: 'Invalid password provided',
emptyBody: 'Server unable to process the recieved data',
unkownEmail: "A user with the provided email doesn't exist",
invalidLink: 'Invalid link provided',
incorectPassword: 'Incorect password provided'
};
15 changes: 8 additions & 7 deletions src/helpers/error.sender.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,18 @@
* A function to create an error object and use the the
* res object to send it back to the client
* @param {Number} status - The status code to send back
* @param {object} resultObj - The result object to structure
* before to send back
* @param {Object} res - The res object
* @param {String} field - the invalid filed rasing the error
* @param {String} error - THe error message to send
* @returns {Boolean} true
*/
const sendError = (status, resultObj, res, error) => {
const obj = resultObj;
obj.status = status;
obj.message = error;
res.status(status).json(obj);
const sendError = (status, res, field, error) => {
const resultObj = {
status,
errors: {}
};
resultObj.errors[field] = error;
res.status(status).json(resultObj);
return true;
};

Expand Down
15 changes: 10 additions & 5 deletions src/middlewares/validations/body.inputs.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,18 +56,23 @@ export default (useJoiError, schema, fields) => {
next();
} else {
// Building the error object
let message = err.details[0].message.replace(/['"]/g, '');
const joiError = {};
joiError.message = err.details[0].message.replace(/['"]/g, '');
// Building a custom error message
fields.find((el) => {
if (message.includes(`${el} with value`) || message.includes(`${el} must be`)) {
message = errorMessages[el];
if (
joiError.message.includes(`${el} with value`)
|| joiError.message.includes(`${el} must be`)
) {
joiError.message = errorMessages[el];
joiError.field = el;
}
return true;
});
if (UseJoiError) {
sendError(status.BAD_REQUEST, {}, res, message);
sendError(status.BAD_REQUEST, res, joiError.field, joiError.message);
} else {
sendError(status.BAD_REQUEST, {}, res, errorMessages.defaultError);
sendError(status.BAD_REQUEST, res, 'body', errorMessages.defaultError);
}
}
});
Expand Down
4 changes: 2 additions & 2 deletions src/middlewares/validations/body.verifier.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import _ from 'lodash';
import sendError from '../../helpers/error.sender';
import status from '../../helpers/constants/status.codes';
import errors from '../../helpers/constants/error.messages';

/**
* A function to verify if the provided body is empty
Expand All @@ -11,7 +12,6 @@ import status from '../../helpers/constants/status.codes';
* or the next callback
*/
export default (req, res, next) => {
const error = 'Server unable to process the recieved data';
if (_.isEmpty(req.body)) sendError(status.BAD_REQUEST, {}, res, error);
if (_.isEmpty(req.body)) sendError(status.BAD_REQUEST, res, 'body', errors.emptyBody);
else next();
};
4 changes: 2 additions & 2 deletions src/middlewares/validations/validate.reset.email.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import models from '../../api/models';
import sendError from '../../helpers/error.sender';
import status from '../../helpers/constants/status.codes';
import errors from '../../helpers/constants/error.messages';
/**
* A function to verify if the provided email exists in the database
* @param {Object} req - The request object
Expand All @@ -19,7 +20,6 @@ export default async (req, res, next) => {
req.user = tempUser.dataValues;
next();
} catch (error) {
const message = "A user with the provided email doesn't exist";
sendError(status.NOT_FOUND, {}, res, message);
sendError(status.NOT_FOUND, res, 'email', errors.unkownEmail);
}
};
4 changes: 2 additions & 2 deletions src/middlewares/validations/validate.reset.link.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import sendError from '../../helpers/error.sender';
import decodeJwt from '../../helpers/tokens/decode.token';
import status from '../../helpers/constants/status.codes';
import errors from '../../helpers/constants/error.messages';

/**
* A function to verify if the provided link is still valid then decode it
Expand All @@ -18,7 +19,6 @@ export default (req, res, next) => {
req.userEmail = decoded.email;
next();
} catch (error) {
const err = 'Invalid link provided';
sendError(status.BAD_REQUEST, {}, res, err);
sendError(status.BAD_REQUEST, res, 'link', errors.invalidLink);
}
};
7 changes: 3 additions & 4 deletions src/middlewares/validations/validate.update.password.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import models from '../../api/models';
import sendError from '../../helpers/error.sender';
import validationSchemas from '../../helpers/constants/validation.schemas';
import status from '../../helpers/constants/status.codes';
import errors from '../../helpers/constants/error.messages';

/**
* A function to validate the an email provided in the url parms
Expand All @@ -24,12 +25,10 @@ export default async (req, res, next) => {
req.user = tempUser.dataValues;
next();
} catch (TypeError) {
const message = "A user with the provided email doesn't exist";
sendError(status.NOT_FOUND, {}, res, message);
sendError(status.NOT_FOUND, res, 'email', errors.unkownEmail);
}
} else {
const error = 'Invalid email provided';
sendError(status.BAD_REQUEST, {}, res, error);
sendError(status.BAD_REQUEST, res, 'email', errors.email);
}
});
};
Loading

0 comments on commit 8cb6b27

Please sign in to comment.