buildURL.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict'
  2. import * as utils from '../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. export default function buildURL(url, params) {
  21. /* eslint no-param-reassign:0 */
  22. if (!params) {
  23. return url
  24. }
  25. let serializedParams
  26. if (utils.isURLSearchParams(params)) {
  27. serializedParams = params.toString()
  28. } else {
  29. const parts = []
  30. utils.forEach(params, (val, key) => {
  31. if (val === null || typeof val === 'undefined') {
  32. return
  33. }
  34. if (utils.isArray(val)) {
  35. key = `${key}[]`
  36. } else {
  37. val = [val]
  38. }
  39. utils.forEach(val, (v) => {
  40. if (utils.isDate(v)) {
  41. v = v.toISOString()
  42. } else if (utils.isObject(v)) {
  43. v = JSON.stringify(v)
  44. }
  45. parts.push(`${encode(key)}=${encode(v)}`)
  46. })
  47. })
  48. serializedParams = parts.join('&')
  49. }
  50. if (serializedParams) {
  51. const hashmarkIndex = url.indexOf('#')
  52. if (hashmarkIndex !== -1) {
  53. url = url.slice(0, hashmarkIndex)
  54. }
  55. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams
  56. }
  57. return url
  58. }