2020-10-22 03:31:58 -05:00
|
|
|
import memoizeOne from 'memoize-one';
|
|
|
|
import { getBackendSrv, config } from '@grafana/runtime';
|
|
|
|
import { copyStringToClipboard } from './explore';
|
2021-03-15 09:11:52 -05:00
|
|
|
import { dispatch } from 'app/store/store';
|
|
|
|
import { notifyApp } from 'app/core/actions';
|
|
|
|
import { createErrorNotification, createSuccessNotification } from 'app/core/copy/appNotification';
|
2020-10-22 03:31:58 -05:00
|
|
|
|
|
|
|
function buildHostUrl() {
|
|
|
|
return `${window.location.protocol}//${window.location.host}${config.appSubUrl}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
function getRelativeURLPath(url: string) {
|
|
|
|
let path = url.replace(buildHostUrl(), '');
|
|
|
|
return path.startsWith('/') ? path.substring(1, path.length) : path;
|
|
|
|
}
|
|
|
|
|
2021-01-20 00:59:48 -06:00
|
|
|
export const createShortLink = memoizeOne(async function (path: string) {
|
2020-10-22 03:31:58 -05:00
|
|
|
try {
|
|
|
|
const shortLink = await getBackendSrv().post(`/api/short-urls`, {
|
|
|
|
path: getRelativeURLPath(path),
|
|
|
|
});
|
|
|
|
return shortLink.url;
|
|
|
|
} catch (err) {
|
|
|
|
console.error('Error when creating shortened link: ', err);
|
2021-03-15 09:11:52 -05:00
|
|
|
dispatch(notifyApp(createErrorNotification('Error generating shortened link')));
|
2020-10-22 03:31:58 -05:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
export const createAndCopyShortLink = async (path: string) => {
|
|
|
|
const shortLink = await createShortLink(path);
|
|
|
|
if (shortLink) {
|
|
|
|
copyStringToClipboard(shortLink);
|
2021-03-15 09:11:52 -05:00
|
|
|
dispatch(notifyApp(createSuccessNotification('Shortened link copied to clipboard')));
|
2020-10-22 03:31:58 -05:00
|
|
|
} else {
|
2021-03-15 09:11:52 -05:00
|
|
|
dispatch(notifyApp(createErrorNotification('Error generating shortened link')));
|
2020-10-22 03:31:58 -05:00
|
|
|
}
|
|
|
|
};
|