append-query
Advanced tools
Comparing version 1.0.0 to 1.1.0
34
index.js
@@ -7,8 +7,34 @@ var querystring = require('querystring') | ||
var parts = url.parse(uri, true) | ||
, parsedQuery = typeof q === 'string' ? querystring.parse(q) : q | ||
, parsedQuery = extend(true, {}, parts.query, typeof q === 'string' ? querystring.parse(q) : q) | ||
extend(parts.query, parsedQuery) | ||
// it's necessary to delete parts.search so parts.query will be used | ||
delete parts.search | ||
parts.search = '?' + serialize(parsedQuery) | ||
return url.format(parts) | ||
} | ||
// serialize an object recursively | ||
function serialize(obj, prefix) { | ||
var str = [] | ||
, useArraySyntax = false | ||
// if there's a prefix, and this object is an array, use array syntax | ||
// i.e., `prefix[]=foo&prefix[]=bar` instead of `prefix[0]=foo&prefix[1]=bar` | ||
if (Array.isArray(obj) && prefix) { | ||
useArraySyntax = true | ||
} | ||
Object.keys(obj).forEach(function (prop) { | ||
var key, query, val = obj[prop] | ||
key = prefix ? | ||
prefix + '[' + (useArraySyntax ? '' : prop) + ']' : | ||
prop | ||
query = typeof val === 'object' ? | ||
serialize(val, key) : | ||
encodeURIComponent(key) + '=' + encodeURIComponent(val) | ||
str.push(query) | ||
}) | ||
return str.join('&') | ||
} |
{ | ||
"name": "append-query", | ||
"version": "1.0.0", | ||
"version": "1.1.0", | ||
"description": "Append querystring params to a URL.", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -0,1 +1,3 @@ | ||
[![Build Status](https://travis-ci.org/lakenen/node-append-query.png?branch=master)](https://travis-ci.org/lakenen/node-append-query) | ||
# append-query | ||
@@ -33,2 +35,10 @@ | ||
## Change Log | ||
* **1.1.0** | ||
- add support for recursive serialization of nested objects | ||
- add support for arrays as properties | ||
## License | ||
@@ -35,0 +45,0 @@ |
@@ -24,1 +24,15 @@ var test = require('tape') | ||
}) | ||
test('should append query object with nested properties to url', function (t) { | ||
t.plan(1) | ||
var result = appendQuery('http://example.com/', { beep: { boop: 'bop' } }) | ||
, expected = 'http://example.com/?beep%5Bboop%5D=bop' | ||
t.equal(result, expected, 'should be equal') | ||
}) | ||
test('should append query object with an array to url', function (t) { | ||
t.plan(1) | ||
var result = appendQuery('http://example.com/', { beep: ['boop', 'bop'] }) | ||
, expected = 'http://example.com/?beep%5B%5D=boop&beep%5B%5D=bop' | ||
t.equal(result, expected, 'should be equal') | ||
}) |
5163
7
62
48