Refactor query string building

This commit is contained in:
Robin North
2018-03-01 10:19:35 +00:00
parent ca479618fe
commit 4e805ad8af
2 changed files with 16 additions and 13 deletions

View File

@@ -2,6 +2,7 @@ var updateQueryString = require("./util/update-query-string");
module.exports = function(location, options, callback) {
options = options || {}
var queryString
var requestMethod = (options.requestMethod || "GET").toUpperCase()
var requestParams = options.requestParams || null
var requestPayload = null
@@ -29,22 +30,23 @@ module.exports = function(location, options, callback) {
// Prepare the request payload for forms, if available
if (requestParams && requestParams.length) {
// Build query string
queryString = (requestParams.map(function(param) {return param.name + "=" + param.value})).join("&")
switch (requestMethod) {
case "GET":
// Reset query string to avoid an issue with repeat submissions where checkboxes that were
// previously checked are incorrectly preserved
location = location.split("?")[0]
// Build new query string
requestParams.forEach(function(param) {
location = updateQueryString(location, param.name, param.value)
});
break;
// Append new query string
location += "?" + queryString
break
case "POST":
// Build payload string
requestPayload = (requestParams.map(function(param) {return param.name + "=" + param.value})).join("&")
break;
// Send query string as request payload
requestPayload = queryString
break
}
}