url.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * @preserve jquery-param (c) 2015 KNOWLEDGECODE | MIT
  3. */
  4. import { UrlQueryMap } from '@grafana/runtime';
  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: string, pctEncodeSpaces?: boolean) {
  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: any) {
  21. const s: any[] = [];
  22. const rbracket = /\[\]$/;
  23. const isArray = (obj: any) => {
  24. return Object.prototype.toString.call(obj) === '[object Array]';
  25. };
  26. const add = (k: string, v: any) => {
  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: string, obj: any) => {
  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. }
  65. export function appendQueryToUrl(url: string, stringToAppend: string) {
  66. if (stringToAppend !== undefined && stringToAppend !== null && stringToAppend !== '') {
  67. const pos = url.indexOf('?');
  68. if (pos !== -1) {
  69. if (url.length - pos > 1) {
  70. url += '&';
  71. }
  72. } else {
  73. url += '?';
  74. }
  75. url += stringToAppend;
  76. }
  77. return url;
  78. }