Skip to content

Commit 3003223

Browse files
committed
backport: custom params serializer support for v0.x
originally implemented in axios#5113
1 parent ce46346 commit 3003223

File tree

4 files changed

+38
-6
lines changed

4 files changed

+38
-6
lines changed

lib/core/Axios.js

+7
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,13 @@ Axios.prototype.request = function request(configOrUrl, config) {
6161

6262
var paramsSerializer = config.paramsSerializer;
6363

64+
if (paramsSerializer !== undefined) {
65+
validator.assertOptions(paramsSerializer, {
66+
encode: validators.function,
67+
serialize: validators.function
68+
}, true);
69+
}
70+
6471
utils.isFunction(paramsSerializer) && (config.paramsSerializer = {serialize: paramsSerializer});
6572

6673
// filter out skipped interceptors

lib/helpers/buildURL.js

+13-5
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,20 @@ module.exports = function buildURL(url, params, options) {
3535

3636
var _encode = options && options.encode || encode;
3737

38-
var serializerParams = utils.isURLSearchParams(params) ?
39-
params.toString() :
40-
new AxiosURLSearchParams(params, options).toString(_encode);
38+
var serializeFn = options && options.serialize;
4139

42-
if (serializerParams) {
43-
url += (url.indexOf('?') === -1 ? '?' : '&') + serializerParams;
40+
var serializedParams;
41+
42+
if (serializeFn) {
43+
serializedParams = serializeFn(params, options);
44+
} else {
45+
serializedParams = utils.isURLSearchParams(params) ?
46+
params.toString() :
47+
new AxiosURLSearchParams(params, options).toString(_encode);
48+
}
49+
50+
if (serializedParams) {
51+
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
4452
}
4553

4654
return url;

test/specs/helpers/buildURL.spec.js

+16
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,20 @@ describe('helpers::buildURL', function () {
6363
it('should support URLSearchParams', function () {
6464
expect(buildURL('/foo', new URLSearchParams('bar=baz'))).toEqual('/foo?bar=baz');
6565
});
66+
67+
it('should support custom serialize function', function () {
68+
var params = {
69+
x: 1
70+
}
71+
72+
var options = {
73+
serialize: (thisParams, thisOptions) => {
74+
expect(thisParams).toEqual(params);
75+
expect(thisOptions).toEqual(options);
76+
return 'rendered'
77+
}
78+
};
79+
80+
expect(buildURL('/foo', params, options)).toEqual('/foo?rendered');
81+
});
6682
});

test/typescript/axios.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ const config: AxiosRequestConfig = {
2222
params: { id: 12345 },
2323
paramsSerializer: {
2424
indexes: true,
25-
encode: (value) => value
25+
encode: (value) => value,
26+
serialize: (value, options) => String(value)
2627
},
2728
data: { foo: 'bar' },
2829
timeout: 10000,

0 commit comments

Comments
 (0)