Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 3dc5d0c

Browse files
committed
feat($httpParamSerializerJQLike): honor object.toJSON function if present.
1 parent 7ffb2d3 commit 3dc5d0c

File tree

2 files changed

+51
-2
lines changed

2 files changed

+51
-2
lines changed

src/ng/http.js

+9-2
Original file line numberDiff line numberDiff line change
@@ -112,12 +112,19 @@ function $HttpParamSerializerJQLikeProvider() {
112112
return parts.join('&');
113113

114114
function serialize(toSerialize, prefix, topLevel) {
115-
if (toSerialize === null || isUndefined(toSerialize)) return;
115+
if (toSerialize === null || isUndefined(toSerialize) || isFunction(toSerialize)) return;
116116
if (isArray(toSerialize)) {
117117
forEach(toSerialize, function(value, index) {
118118
serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
119119
});
120-
} else if (isObject(toSerialize) && !isDate(toSerialize)) {
120+
} else if (isFunction(toSerialize.toJSON)) {
121+
var toJsonResult = toSerialize.toJSON();
122+
if (isString(toJsonResult)) {
123+
parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(toJsonResult));
124+
} else {
125+
serialize(toJsonResult, prefix, topLevel);
126+
}
127+
} else if (isObject(toSerialize)) {
121128
forEachSorted(toSerialize, function(value, key) {
122129
serialize(value, prefix +
123130
(topLevel ? '' : '[') +

test/ng/httpSpec.js

+42
Original file line numberDiff line numberDiff line change
@@ -2049,6 +2049,48 @@ describe('$http param serializers', function() {
20492049
expect(jqrSer({someDate: new Date('2014-07-15T17:30:00.000Z')})).toEqual('someDate=2014-07-15T17:30:00.000Z');
20502050
});
20512051

2052+
it('should ignore functions', function() {
2053+
expect(jqrSer({
2054+
foo: {
2055+
a: 'b',
2056+
c: function() {
2057+
return 'd';
2058+
}
2059+
}
2060+
})).toEqual('foo%5Ba%5D=b');
2061+
});
2062+
2063+
it('should honor toJSON function which returns a string', function() {
2064+
expect(jqrSer({
2065+
foo: {
2066+
a: 'b',
2067+
toJSON: function() {
2068+
return 'baz';
2069+
}
2070+
},
2071+
bar: {
2072+
c: 'd'
2073+
}
2074+
})).toEqual('bar%5Bc%5D=d&foo=baz');
2075+
});
2076+
2077+
it('should honor toJSON function which returns an object', function() {
2078+
expect(jqrSer({
2079+
foo: {
2080+
a: 'b',
2081+
toJSON: function() {
2082+
return {
2083+
e: 'f',
2084+
g: 'h'
2085+
};
2086+
}
2087+
},
2088+
bar: {
2089+
c: 'd'
2090+
}
2091+
})).toEqual('bar%5Bc%5D=d&foo%5Be%5D=f&foo%5Bg%5D=h');
2092+
});
2093+
20522094
});
20532095

20542096
describe('default array serialization', function() {

0 commit comments

Comments
 (0)