Skip to content

Commit

Permalink
Create helper functions
Browse files Browse the repository at this point in the history
  • Loading branch information
abidex4yemi committed Jul 17, 2019
1 parent 09f1d07 commit 8cf6533
Show file tree
Hide file tree
Showing 4 changed files with 83 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/server/util/error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict';

/**
* Define error constants
*/
export const BAD_REQUEST = 400;
export const CONFLICT = 409;
export const NOT_FOUND = 404;
export const GENERIC_ERROR = 500;

/**
* Wrapper for javascript native Error() constructor
*
* @param {String} message
* @param {number} status
*
* @returns {object} error
*/
export const createError = ({ message = 'Something went wrong, try again...', status = 500 }) => {
const error = new Error(message);
error.status = status;

return error;
};
4 changes: 4 additions & 0 deletions src/server/util/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// Export all utility files
export { createError, BAD_REQUEST, CONFLICT, NOT_FOUND, GENERIC_ERROR } from './error';
export { OK, CREATED, createSuccess } from './success';
export { joiValidate } from './joiValidate';
32 changes: 32 additions & 0 deletions src/server/util/joiValidate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import Joi from '@hapi/joi';

/**
* Validate request body
*
* @param {object} req
* @param {object} res
* @param {object} next
* @param {object} schema
*/
export const joiValidate = (req, res, next, schema) => {
// validate request body against predefined schema
const { error, value } = Joi.validate(req.body, schema, {
abortEarly: false
});

// check for validation error
if (error) {
// Format error object of JOI
const errors = error.details.map(current => ({
key: current.context.key,
message: current.message.replace(/['"]/g, '')
}));

return res.status(400).json({ errors });
}

//Note: create a new key `sanitizedBody` to the body with sanitized value
req.body.sanitizedBody = value;

next();
};
23 changes: 23 additions & 0 deletions src/server/util/success.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
'use strict';

/**
* Define success status constants
*/
export const CREATED = 201;
export const OK = 200;

/**
* Create success response data format wrapper
*
* @param {object} { data, message }
*
*/ export const createSuccess = ({
data,
message = 'successful'
}) => {
return {
success: true,
message,
body: data
};
};

0 comments on commit 8cf6533

Please sign in to comment.