Last active
May 31, 2022 11:44
-
-
Save AhsanAyaz/b5073f845b1f74ce29c1cf75f7b4619d to your computer and use it in GitHub Desktop.
Score Validator JS file for the tutorial
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
const joi = require('joi') | |
const createHttpError = require('http-errors') | |
const addScoreDTO = joi.object().keys({ | |
gameId: joi.string().required(), | |
userId: joi.string().required(), | |
score: joi.number().required(), | |
}); | |
const deleteScoreDTO = joi.object({ | |
userId: joi.string().required(), | |
}); | |
const updateScoreDTO = joi.object().keys({ | |
userId: joi.string().required(), | |
score: joi.number().required(), | |
}); | |
const ScoreDTOValidator = (validator) => { | |
return async function (req, res, next) { | |
try { | |
const validatedBody = await validator.validateAsync(req.body) | |
req.body = validatedBody | |
next() | |
} catch (err) { | |
if (err.isJoi) { | |
return next(createHttpError(422, { message: err.message })) | |
} | |
next(createHttpError(500)) | |
} | |
} | |
} | |
module.exports = { | |
addScoreDTO, | |
deleteScoreDTO, | |
updateScoreDTO, | |
ScoreDTOValidator | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment