buildURL.js 1.6 KB

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