Cleaned up code for the response-saver

This commit is contained in:
Alicia Sykes
2018-01-26 22:22:50 +00:00
parent d6d74bd022
commit 141c4e257a
2 changed files with 28 additions and 12 deletions

View File

@@ -18,18 +18,16 @@ let teamRecordSchema = new Schema({
]
});
function checkInputIsValidJson(input) {
return (/^[\],:{}\s]*$/.test(input.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, '')));
}
/**
* Adds a new user response
* @param userResponse
* @returns {*}
*/
teamRecordSchema.statics.insertUserResponse = (userResponse) => {
const rs = new ResponseSaver();
return rs.insertUserResponse(userResponse);
};
const TeamRecordSchema = mongoose.model('TeamRecord', teamRecordSchema);
module.exports = TeamRecordSchema;

View File

@@ -10,10 +10,11 @@ class ResponseSaver {
return new Promise((resolve, reject) => {
// if (!checkInputIsValidJson(userResponse)){
// errorMessage = "Malformed input. Must be valid JSON.";
// return reject(new TypeError(errorMessage));
// }
/* Ensure that the input is of a valid format */
if (!ResponseSaver.checkInputIsValidJson(userResponse)){
errorMessage = "Malformed input. Must be valid JSON.";
return reject(new TypeError(errorMessage));
}
// TODO check if userhash is part of a valid team
TeamMembersModel.find({ }, function(err, teams) {
teams.forEach((team)=>{
@@ -47,11 +48,28 @@ class ResponseSaver {
_userResponse.save((err, saved) => {
err ? reject(err)
: resolve(saved);
: resolpve(saved);
});
});
}
/**
* Determines weather input is of a valid format
* @param input
* @returns {boolean}
*/
static checkInputIsValidJson(input) {
if (typeof input === 'string' || input instanceof String) {
return (/^[\],:{}\s]*$/.test(input
.replace(/\\["\\\/bfnrtu]/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, '')));
}
else {
return (typeof input === 'object' || input instanceof Object);
}
}
}
module.exports = ResponseSaver;