|
211 | 211 |
|
212 | 212 | //TODO: support arrays as values |
213 | 213 | if (null !== call.params[key] && call.params.hasOwnProperty(key)) { |
214 | | - params.push( |
215 | | - // Keys and values must be encoded to |
216 | | - // prevent accidental breakage of string |
217 | | - // splits by `=` and `&`. |
218 | | - encodeURIComponent(key) + |
219 | | - "=" + |
220 | | - encodeURIComponent(call.params[key]) |
221 | | - ); |
| 214 | + params.push(parameterize(key, call.params[key])); |
222 | 215 | } |
223 | 216 | } |
224 | 217 |
|
|
227 | 220 | return params.join('&'); |
228 | 221 | }; |
229 | 222 |
|
| 223 | + var parameterize = function(key, value) { |
| 224 | + var type = typeof value; |
| 225 | + switch (type) { |
| 226 | + case 'string': |
| 227 | + case 'number': |
| 228 | + case 'boolean': |
| 229 | + return parameterizePrimitive(key, value); |
| 230 | + break; |
| 231 | + |
| 232 | + case 'object': |
| 233 | + // `null` is considered an "object" |
| 234 | + return (null === value) ? parameterizePrimitive(key, value) : parameterizeObject(key, value); |
| 235 | + break; |
| 236 | + |
| 237 | + default: |
| 238 | + throw new Error("Unable to parameterize key " + key + " with type " + type); |
| 239 | + } |
| 240 | + }; |
| 241 | + |
| 242 | + var parameterizePrimitive = function(key, value) { |
| 243 | + // Keys and values must be encoded to |
| 244 | + // prevent accidental breakage of string |
| 245 | + // splits by `=` and `&`. |
| 246 | + return encodeURIComponent(key) + "=" + encodeURIComponent(value); |
| 247 | + }; |
| 248 | + |
| 249 | + var parameterizeObject = function(key, value) { |
| 250 | + var params = []; |
| 251 | + if (Array.isArray(value)) { |
| 252 | + for (var i = 0, len = value.length; i < len; i++) { |
| 253 | + params.push(encodeURIComponent(key) + "[]=" + encodeURIComponent(value[i])); |
| 254 | + } |
| 255 | + } else { |
| 256 | + // assume object |
| 257 | + for (var subkey in value) { |
| 258 | + if (!value.hasOwnProperty(subkey)) continue; |
| 259 | + params.push(encodeURIComponent(key) + "[" + encodeURIComponent(subkey) + "]=" + encodeURIComponent(value[subkey])); |
| 260 | + } |
| 261 | + } |
| 262 | + |
| 263 | + return params.join('&'); |
| 264 | + }; |
| 265 | + |
230 | 266 | // Recursively merge properties of two objects |
231 | 267 | // Adapted from http://stackoverflow.com/a/383245/249394 |
232 | 268 | function mergeRecursive(obj1, obj2) { |
|
0 commit comments