joinQuery.js
1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"use strict";
// TODO :: use "querystring" package (that node uses) -- create PR for `skipEmpties`?
function joinQuery(queryObj, skipEmpties)
{
var i,len,value,varname;
var count = { i:0 }; // literals do not persist across functions
var output = "";
for (varname in queryObj)
{
if (queryObj.hasOwnProperty(varname)===true)
{
value = queryObj[varname];
// "?var1=a&var1=b" would've been parsed to { var1: ["a","b"] }
if (Array.isArray(value) === false)
{
output += joinValue(varname, value, count, skipEmpties);
}
else
{
len = value.length;
for (i=0; i<len; i++)
{
output += joinValue(varname, value[i], count, skipEmpties);
}
}
}
}
return output;
}
/*
Creates "?var=value" or "&var=value".
*/
function joinValue(varname, value, count, skipEmpties)
{
var output = "";
// If accept or ignore "?=" and "?query="
if ((varname!=="" && value!=="") || skipEmpties!==true)
{
output += (++count.i>1) ? "&" : "?";
varname = encodeURIComponent(varname);
if (value !== "")
{
// "?query=this+is+a+value"
output += varname +"="+ encodeURIComponent(value).replace(/%20/g,"+");
}
else
{
// "?query="
output += varname+"=";
}
}
return output;
}
module.exports = joinQuery;