buildURL.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. var utils = require('./../utils');
  3. function encode(val) {
  4. return encodeURIComponent(val).
  5. replace(/%40/gi, '@').
  6. replace(/%3A/gi, ':').
  7. replace(/%24/g, '$').
  8. replace(/%2C/gi, ',').
  9. replace(/%20/g, '+').
  10. replace(/%5B/gi, '[').
  11. replace(/%5D/gi, ']');
  12. }
  13. /**
  14. * Build a URL by appending params to the end
  15. *
  16. * @param {string} url The base of the url (e.g., http://www.google.com)
  17. * @param {object} [params] The params to be appended
  18. * @returns {string} The formatted url
  19. */
  20. module.exports = function buildURL(url, params, paramsSerializer) {
  21. /*eslint no-param-reassign:0*/
  22. if (!params) {
  23. return url;
  24. }
  25. var serializedParams;
  26. if (paramsSerializer) {
  27. serializedParams = paramsSerializer(params);
  28. } else if (utils.isURLSearchParams(params)) {
  29. serializedParams = params.toString();
  30. } else {
  31. var parts = [];
  32. utils.forEach(params, function serialize(val, key) {
  33. if (val === null || typeof val === 'undefined') {
  34. return;
  35. }
  36. if (utils.isArray(val)) {
  37. key = key + '[]';
  38. }
  39. if (!utils.isArray(val)) {
  40. val = [val];
  41. }
  42. utils.forEach(val, function parseValue(v) {
  43. if (utils.isDate(v)) {
  44. v = v.toISOString();
  45. } else if (utils.isObject(v)) {
  46. v = JSON.stringify(v);
  47. }
  48. parts.push(encode(key) + '=' + encode(v));
  49. });
  50. });
  51. serializedParams = parts.join('&');
  52. }
  53. if (serializedParams) {
  54. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  55. }
  56. return url;
  57. };