url.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * @preserve jquery-param (c) 2015 KNOWLEDGECODE | MIT
  3. */
  4. import { UrlQueryMap } from 'app/types';
  5. export function renderUrl(path: string, query: UrlQueryMap | undefined): string {
  6. if (query && Object.keys(query).length > 0) {
  7. path += '?' + toUrlParams(query);
  8. }
  9. return path;
  10. }
  11. export function encodeURIComponentAsAngularJS(val, pctEncodeSpaces) {
  12. return encodeURIComponent(val).
  13. replace(/%40/gi, '@').
  14. replace(/%3A/gi, ':').
  15. replace(/%24/g, '$').
  16. replace(/%2C/gi, ',').
  17. replace(/%3B/gi, ';').
  18. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  19. }
  20. export function toUrlParams(a) {
  21. const s = [];
  22. const rbracket = /\[\]$/;
  23. const isArray = obj => {
  24. return Object.prototype.toString.call(obj) === '[object Array]';
  25. };
  26. const add = (k, v) => {
  27. v = typeof v === 'function' ? v() : v === null ? '' : v === undefined ? '' : v;
  28. if (typeof v !== 'boolean') {
  29. s[s.length] = encodeURIComponentAsAngularJS(k, true) + '=' + encodeURIComponentAsAngularJS(v, true);
  30. } else {
  31. s[s.length] = encodeURIComponentAsAngularJS(k, true);
  32. }
  33. };
  34. const buildParams = (prefix, obj) => {
  35. let i, len, key;
  36. if (prefix) {
  37. if (isArray(obj)) {
  38. for (i = 0, len = obj.length; i < len; i++) {
  39. if (rbracket.test(prefix)) {
  40. add(prefix, obj[i]);
  41. } else {
  42. buildParams(prefix, obj[i]);
  43. }
  44. }
  45. } else if (obj && String(obj) === '[object Object]') {
  46. for (key in obj) {
  47. buildParams(prefix + '[' + key + ']', obj[key]);
  48. }
  49. } else {
  50. add(prefix, obj);
  51. }
  52. } else if (isArray(obj)) {
  53. for (i = 0, len = obj.length; i < len; i++) {
  54. add(obj[i].name, obj[i].value);
  55. }
  56. } else {
  57. for (key in obj) {
  58. buildParams(key, obj[key]);
  59. }
  60. }
  61. return s;
  62. };
  63. return buildParams('', a).join('&');
  64. }