diff --git a/src/index.js b/src/index.js index f4c86f2..8627c83 100644 --- a/src/index.js +++ b/src/index.js @@ -63,6 +63,32 @@ export default (function create(defaults) { return (url, data, config) => redaxios(url, Object.assign({ method, data }, config)); } + /** + * Builds request url based on query string parameters + * @private + * @param {string} url + * @param {object|URLSearchParams} [params] + * @param {function} [serializer] + * @returns {string} + */ + function buildUrl(url, params, serializer) { + if (!params) { + return url; + } + + let serializedParams; + if (serializer) { + serializedParams = serializer(params); + } else if (params instanceof URLSearchParams) { + serializedParams = params.toString(); + } else { + serializedParams = (new URLSearchParams(params)).toString(); + } + + const divider = url.indexOf('?') === -1 ? '?' : '&'; + return url + divider + serializedParams; + } + /** * @public * @type {((config?: Options) => Promise) | ((url: string, config?: Options) => Promise)} @@ -133,6 +159,7 @@ export default (function create(defaults) { } const options = deepMerge(defaults, config || {}); let data = options.data; + url = buildUrl(url, options.params, options.paramsSerializer); if (options.transformRequest) { for (let i = 0; i < options.transformRequest.length; i++) { @@ -142,7 +169,7 @@ export default (function create(defaults) { } } } - + const fetchFunc = options.fetch || fetch; const customHeaders = {}; diff --git a/test/index.test.js b/test/index.test.js index 8327ba5..21d9949 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -83,4 +83,34 @@ describe('redaxios', () => { expect(res.status).toEqual(200); expect(JSON.parse(res.data)).toEqual({ hello: 'world' }); }); + + it('should support params and paramsSerializer options', async () => { + const oldFetch = window.fetch; + window.fetch = jasmine.createSpy('fetch').and.returnValue(Promise.resolve()); + + axios.get('/foo'); + expect(window.fetch).toHaveBeenCalledTimes(1); + expect(window.fetch).toHaveBeenCalledWith('/foo', jasmine.any(Object)); + + let params = { a: 1, b: true }; + axios.get('/foo', { params }); + expect(window.fetch).toHaveBeenCalledTimes(2); + expect(window.fetch).toHaveBeenCalledWith('/foo?a=1&b=true', jasmine.any(Object)); + + axios.get('/foo?c=42', { params }); + expect(window.fetch).toHaveBeenCalledTimes(3); + expect(window.fetch).toHaveBeenCalledWith('/foo?c=42&a=1&b=true', jasmine.any(Object)); + + params = new URLSearchParams({ d: 'test' }); + axios.get('/foo', { params }); + expect(window.fetch).toHaveBeenCalledTimes(4); + expect(window.fetch).toHaveBeenCalledWith('/foo?d=test', jasmine.any(Object)); + + const paramsSerializer = params => 'e=iamthelaw'; + axios.get('/foo', { params, paramsSerializer }); + expect(window.fetch).toHaveBeenCalledTimes(5); + expect(window.fetch).toHaveBeenCalledWith('/foo?e=iamthelaw', jasmine.any(Object)); + + window.fetch = oldFetch; + }); });