Skip to content

Commit

Permalink
Satisfy url parameter tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mikemonteith committed Mar 23, 2020
1 parent a19c89a commit b4e8493
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
2 changes: 2 additions & 0 deletions lib/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ const insertOrUpdate = async (data) => {

/**
* @param {Object} payload - data to save for the initial response
* @param {boolean} payload.isSatisfied - is the user satisfied?
* @param {string} payload.url - URL that the user is commenting on
* @returns {Promise}
*/
module.exports.saveInitialResponse = (payload) => {
Expand Down
1 change: 1 addition & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ module.exports.handleRequest = async (context, req, requestType) => {
token = await database.saveInitialResponse({
isSatisfied: req.body.isSatisfied,
token,
url: req.body.url,
});
}
if (requestType === requestTypes.COMMENTS) {
Expand Down
22 changes: 20 additions & 2 deletions lib/validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,20 @@ class ValidationError extends HttpError {

module.exports.ValidationError = ValidationError;

/**
* Validates if a given test string is a valid URL
* @param {string} test - The string to test
* @returns {boolean} - True if the test string is a valid URL, otherwise false.
*/
const isValidUrl = (test) => {
try {
new URL(test); // eslint-disable-line no-new
return true;
} catch (_) {
return false;
}
};

/**
* Validate the incoming data and return clean data for saving to the database
* @param {Object} data - Object containing initial response data
Expand All @@ -34,13 +48,17 @@ module.exports.ValidationError = ValidationError;
* @throws {ValidationError} error if data format is invalid
*/
module.exports.validateInitialResponse = (data) => {
const { isSatisfied, token } = data;
const { isSatisfied, token, url } = data;

if (isSatisfied !== true && isSatisfied !== false) {
throw new ValidationError('isSatisfied must be true or false');
}

return { isSatisfied, token };
if (!isValidUrl(url)) {
throw new ValidationError('url must be a valid URL');
}

return { isSatisfied, token, url };
};

/**
Expand Down

0 comments on commit b4e8493

Please sign in to comment.