You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.6 KiB

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