Created
March 3, 2021 10:27
-
-
Save franko4don/ca37c398dd7b2005d8edfb1d0f13b1b5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* istanbul ignore file */ | |
| import constants from '../config/constants.js'; | |
| import dotenv from 'dotenv'; | |
| dotenv.config(); | |
| const { | |
| FAILED, SUCCESS, HTTP_UNPROCESSABLE_ENTITY, | |
| HTTP_NOT_FOUND, HTTP_BAD_REQUEST, HTTP_CONFLICT, | |
| HTTP_FORBIDDEN, HTTP_OK, HTTP_UNAUTHORIZED | |
| } = constants; | |
| class Helpers { | |
| /** | |
| * | |
| * @param {object} errors | |
| * processes the errors returned by the validator and puts it in required format | |
| */ | |
| extractErrors(errors) { | |
| const validationErrors = {}; | |
| errors.map(error => { | |
| if(validationErrors.hasOwnProperty(error.param)){ | |
| validationErrors[error.param].push(error.msg) | |
| }else{ | |
| validationErrors[error.param] = [error.msg]; | |
| } | |
| return validationErrors; | |
| }); | |
| return validationErrors; | |
| } | |
| /** | |
| * | |
| * @param {var} num | |
| * Checks if value is an integer | |
| */ | |
| isANumber(num) { | |
| return Number.isInteger(Number(num)); | |
| } | |
| /** | |
| * | |
| * @param {object} res | |
| * @param {object} errors | |
| * formats response caused due to form validation | |
| */ | |
| validationFailed(res, errors){ | |
| let response = { | |
| status: FAILED, | |
| errors, | |
| status_code: HTTP_UNPROCESSABLE_ENTITY, | |
| message: 'unprocessable entity' | |
| } | |
| return res.status(HTTP_UNPROCESSABLE_ENTITY).send(response) | |
| } | |
| /** | |
| * | |
| * @param {object} res | |
| * @param {string} message | |
| * Formats response for not found | |
| */ | |
| notFound(res, message){ | |
| let response = { | |
| status: FAILED, | |
| status_code: HTTP_NOT_FOUND, | |
| message | |
| } | |
| return res.status(HTTP_NOT_FOUND).send(response) | |
| } | |
| /** | |
| * | |
| * @param {object} res | |
| * @param {string} message | |
| * Formats response for unauthorized requests | |
| */ | |
| expiredToken(res, message){ | |
| let response = { | |
| status: FAILED, | |
| status_code: HTTP_UNAUTHORIZED, | |
| message, | |
| expiredToken: true | |
| } | |
| return res.status(HTTP_UNAUTHORIZED).send(response) | |
| } | |
| /** | |
| * | |
| * @param {object} res | |
| * @param {string} message | |
| * Formats response for unauthorized requests | |
| */ | |
| unauthorized(res, message){ | |
| let response = { | |
| status: FAILED, | |
| status_code: HTTP_UNAUTHORIZED, | |
| message | |
| } | |
| return res.status(HTTP_UNAUTHORIZED).send(response) | |
| } | |
| /** | |
| * | |
| * @param {object} res | |
| * @param {string} message | |
| * Formats response for bad requests | |
| */ | |
| badRequest(res, message){ | |
| let response = { | |
| status: FAILED, | |
| status_code: HTTP_BAD_REQUEST, | |
| message | |
| } | |
| return res.status(HTTP_BAD_REQUEST).send(response) | |
| } | |
| /** | |
| * | |
| * @param {object} res | |
| * @param {string} message | |
| * Formats response for successful action that doesn't require data to be sent back | |
| */ | |
| actionSuccess(res, message){ | |
| let response = { | |
| status: SUCCESS, | |
| status_code: HTTP_OK, | |
| message | |
| } | |
| return res.status(HTTP_OK).send(response) | |
| } | |
| /** | |
| * | |
| * @param {object} res | |
| * @param {string} message | |
| * Formats response for failed action that doesn't require data to be sent back | |
| */ | |
| actionFailure(res, message){ | |
| let response = { | |
| status: FAILED, | |
| status_code: HTTP_CONFLICT, | |
| message | |
| } | |
| return res.status(HTTP_CONFLICT).send(response) | |
| } | |
| /** | |
| * | |
| * @param {object} res | |
| * @param {string} message | |
| * Formats response for forbidden action | |
| */ | |
| forbidden(res, message){ | |
| let response = { | |
| status: FAILED, | |
| status_code: HTTP_FORBIDDEN, | |
| message | |
| } | |
| return res.status(HTTP_FORBIDDEN).send(response) | |
| } | |
| /** | |
| * @param {var} s | |
| */ | |
| isValidUrl(s){ | |
| var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; | |
| return regexp.test(s); | |
| }; | |
| /** | |
| * | |
| * @param {object} res | |
| * @param {string} message | |
| * Formats response for successful action that requires data to be returned | |
| */ | |
| success(res, data, message = 'successful'){ | |
| let response = { | |
| data, | |
| status: SUCCESS, | |
| status_code: HTTP_OK, | |
| message | |
| } | |
| return res.status(HTTP_OK).send(response); | |
| } | |
| /** | |
| * | |
| * @param {object} res | |
| * @param {string} message | |
| * Formats response for successful action that requires data to be returned | |
| */ | |
| successPaginated(res, data, meta={}, message = 'successful'){ | |
| let response = { | |
| data, | |
| status: SUCCESS, | |
| status_code: HTTP_OK, | |
| meta, | |
| message | |
| } | |
| return res.status(HTTP_OK).send(response); | |
| } | |
| getPaginationOptions(req){ | |
| let page = parseInt(req.query.page, 10) || 1; | |
| let limit = parseInt(req.query.limit, 10) || 60; | |
| let skipper = page > 0 ? (page - 1) * limit: page * limit; | |
| return { | |
| page, limit, skipper | |
| } | |
| } | |
| getMeta(pageOptions, total){ | |
| return { | |
| totalPages: total % pageOptions.limit == 0 ? parseInt(total / pageOptions.limit) : parseInt(total / pageOptions.limit) + 1, | |
| limit: pageOptions.limit, | |
| page: pageOptions.page | |
| } | |
| } | |
| /** | |
| * Generates random n digit invite code that is unique to a user | |
| * @param {int} length | |
| */ | |
| async randomString(length = 10){ | |
| let alpha = "ABCDEFGHIJKLMNOPQRSTUPWXYZ0123456789abcdefghijklmnopqrstuvwxyz".split(''); | |
| let code = ''; | |
| for(let i = 0; i < length; i++){ | |
| // code += this.getRandomInt(alpha.length - 1); | |
| code += alpha[Math.floor(Math.random() * Math.floor(alpha.length - 1))]; | |
| } | |
| return code; | |
| } | |
| slugify(string){ | |
| const a = 'àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïíīįìłḿñńǹňôöòóœøōõőṕŕřßśšşșťțûüùúūǘůűųẃẍÿýžźż·/_,:;' | |
| const b = 'aaaaaaaaaacccddeeeeeeeegghiiiiiilmnnnnoooooooooprrsssssttuuuuuuuuuwxyyzzz------' | |
| const p = new RegExp(a.split('').join('|'), 'g') | |
| if(!string) return ''; | |
| return string.toString().toLowerCase() | |
| .replace(/\s+/g, '-') // Replace spaces with - | |
| .replace(p, c => b.charAt(a.indexOf(c))) // Replace special characters | |
| .replace(/&/g, '-and-') // Replace & with 'and' | |
| .replace(/[^\w\-]+/g, '') // Remove all non-word characters | |
| .replace(/\-\-+/g, '-') // Replace multiple - with single - | |
| .replace(/^-+/, '') // Trim - from start of text | |
| .replace(/-+$/, '') // Trim - from end of text | |
| } | |
| shuffle(array) { | |
| var currentIndex = array.length, temporaryValue, randomIndex; | |
| // While there remain elements to shuffle... | |
| while (0 !== currentIndex) { | |
| // Pick a remaining element... | |
| randomIndex = Math.floor(Math.random() * currentIndex); | |
| currentIndex -= 1; | |
| // And swap it with the current element. | |
| temporaryValue = array[currentIndex]; | |
| array[currentIndex] = array[randomIndex]; | |
| array[randomIndex] = temporaryValue; | |
| } | |
| return array; | |
| } | |
| /** | |
| * gets the ip of the user making request | |
| * @param {Object} request | |
| */ | |
| getUserIp(request) { | |
| let ip = request.headers['x-forwarded-for'] || | |
| request.connection.remoteAddress || | |
| request.socket.remoteAddress || | |
| request.connection.socket.remoteAddress; | |
| ip = ip.split(',')[0]; | |
| ip = ip.split(':').slice(-1)[0]; //in case the ip returned in a format: "::ffff:146.xxx.xxx.xxx" | |
| return ip; | |
| } | |
| } | |
| export default Helpers; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment