Created
May 17, 2020 17:04
-
-
Save keithics/d6b78205b071c9763bb3f379b2de59f8 to your computer and use it in GitHub Desktop.
Sample Responses
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
// responses | |
export const SuccessResponse = function(res,data) { | |
if(data){ | |
res.json(data) | |
}else{ | |
ErrorResponse(res,{message:'Data is null',code:422}) | |
} | |
} | |
const filterMessage = (err,code) => { | |
if(err?.name == 'ValidationError'){ | |
return {message:ErrorHandlerController.getErrorMessage(err),code:422} | |
} | |
else if(err?.type === 'http'){ | |
return err | |
} | |
else{ | |
Error.create({error:err}) | |
const message = err?.message || 'Unknown Server Error Occurred' | |
return { message, code} | |
} | |
} | |
export const ErrorResponse = (res,err)=>{ | |
try{ | |
const code = err?.code || 500; | |
const errorData = filterMessage(err,code) | |
return res.status(errorData.code).send(errorData); | |
}catch (e) { | |
return res.status(500).send({ | |
message: 'Server Error Occurred' | |
}); | |
} | |
} | |
// route | |
app.route('/mobile/public/otp').post( | |
otpValidation(), Validator.validate, | |
this.userController.otp.bind(this.userController) | |
) | |
// controller | |
public async otp(req, res) { | |
const {phone} = req.body | |
const findInActive = {phone, status:'active'}; | |
const checkUser = await Otp.findOne(findInActive).count() | |
if(checkUser === 1){ | |
ErrorResponse(res,{message:'Phone is already registered',code:422}) | |
}else{ | |
const otp = Helpers.randomNumber(6) | |
sendSMS(otp,phone) | |
Otp.create({status:'inactive',otp,phone,created:Helpers.currentDateTime()}) | |
.then((response) => SuccessResponse(res, {message:'Ok', code:200})) | |
.catch((error) => ErrorResponse(res, error)) | |
} | |
} | |
// OTP validation | |
export function otpValidation () { | |
return [ | |
Validator.required('username'), | |
Validator.required('password'), | |
Validator.required('phone'), | |
Validator.isEmail('username'), | |
Validator.passwordCombination('password'), | |
Validator.isNumber('phone'), | |
Validator.isValidThaiNumber('phone'), | |
] | |
} | |
// Validator Class | |
const { body, validationResult,check } = require('express-validator') | |
export class Validator { | |
static required(field) { | |
return body(field).not().isEmpty().withMessage(field + ' is required') | |
} | |
static isEmail(field){ | |
return body(field).isEmail().withMessage(field + ' must be email format') | |
} | |
static isArray(field){ | |
return body(field).isArray().withMessage(field + ' must be an array') | |
} | |
static isIn(field,values){ | |
return body(field).isIn(values).withMessage(field + ' must be either ' + values.toString()) | |
} | |
static isNumber(field){ | |
return body(field).isInt().withMessage(field + ' must be a number') | |
} | |
static minLength(field,length){ | |
return body(field).isLength({ min: length }).withMessage(field + ' must be at least '+ length+' characters') | |
} | |
static isValidThaiNumber(field){ | |
// starts with zero | |
// 10 in length | |
// must be a number | |
// 0812345678 | |
return body(field) | |
.custom( it =>{ | |
return (it. length === 10 && it.substring(0,1).toString() === '0') | |
}).withMessage(field + ' must be in this format 0812345678') | |
} | |
static minNumber(field,minValue){ | |
return body(field).custom(val=> val > minValue).withMessage(field + ' must be more than '+ minValue) | |
} | |
static passwordCombination(field){ | |
return body(field) | |
.matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/, "i") | |
.withMessage('Password combination 8 in length with at least one uppercase, lower case and special character or number. ') | |
} | |
static validate = (req, res, next) => { | |
const errors = validationResult(req) | |
if (errors.isEmpty()) { | |
return next() | |
} | |
const extractedErrors = [] | |
// errors.array().map(err => extractedErrors.push({ [err.param]: err.msg })) | |
return res.status(422).json({message:errors.array()[0].msg}) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment