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.

69 lines
1.6 KiB

3 years ago
  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. var serializedParams
  26. if (utils.isURLSearchParams(params)) {
  27. serializedParams = params.toString()
  28. } else {
  29. var parts = []
  30. utils.forEach(params, function serialize(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, function parseValue(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. var 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. }