Files
grafana/public/app/plugins/panel/canvas/editor/APIEditor.tsx
Josh Hunt 3c6e0e8ef8 Chore: ESlint import order (#44959)
* Add and configure eslint-plugin-import

* Fix the lint:ts npm command

* Autofix + prettier all the files

* Manually fix remaining files

* Move jquery code in jest-setup to external file to safely reorder imports

* Resolve issue caused by circular dependencies within Prometheus

* Update .betterer.results

* Fix missing // @ts-ignore

* ignore iconBundle.ts

* Fix missing // @ts-ignore
2022-04-22 14:33:13 +01:00

116 lines
2.9 KiB
TypeScript

import React, { FC, useCallback } from 'react';
import { AppEvents, StandardEditorProps, StandardEditorsRegistryItem, StringFieldConfigSettings } from '@grafana/data';
import { config, getBackendSrv } from '@grafana/runtime';
import { Button, InlineField, InlineFieldRow, JSONFormatter, StringValueEditor } from '@grafana/ui';
import { appEvents } from 'app/core/core';
export interface APIEditorConfig {
endpoint: string;
data?: string;
}
const dummyStringSettings: StandardEditorsRegistryItem<string, StringFieldConfigSettings> = {
settings: {},
} as any;
export const callApi = (api: APIEditorConfig, isTest = false) => {
if (api) {
getBackendSrv()
.fetch({
url: api.endpoint!,
method: 'POST',
data: api.data ?? {},
})
.subscribe({
error: (error: any) => {
if (isTest) {
appEvents.emit(AppEvents.alertError, ['Error has occurred: ', JSON.stringify(error)]);
console.error(error);
}
},
complete: () => {
if (isTest) {
appEvents.emit(AppEvents.alertSuccess, ['Test successful']);
}
},
});
}
};
export const APIEditor: FC<StandardEditorProps<APIEditorConfig, any, any>> = (props) => {
const { value, context, onChange } = props;
const labelWidth = 9;
const onEndpointChange = useCallback(
(endpoint) => {
onChange({
...value,
endpoint,
});
},
[onChange, value]
);
const onDataChange = useCallback(
(data) => {
onChange({
...value,
data,
});
},
[onChange, value]
);
const renderJSON = (data: string) => {
try {
const json = JSON.parse(data);
return <JSONFormatter json={json} />;
} catch (error) {
return `Invalid JSON provided: ${error.message}`;
}
};
const renderTestAPIButton = (api: APIEditorConfig) => {
if (api && api.endpoint) {
return (
<Button onClick={() => callApi(api, true)} title={'Test API'}>
Test API
</Button>
);
}
return;
};
return config.disableSanitizeHtml ? (
<>
<InlineFieldRow>
<InlineField label={'Endpoint'} labelWidth={labelWidth} grow={true}>
<StringValueEditor
context={context}
value={value?.endpoint}
onChange={onEndpointChange}
item={dummyStringSettings}
/>
</InlineField>
</InlineFieldRow>
<InlineFieldRow>
<InlineField label={'Data'} labelWidth={labelWidth} grow={true}>
<StringValueEditor
context={context}
value={value?.data ?? '{}'}
onChange={onDataChange}
item={dummyStringSettings}
/>
</InlineField>
</InlineFieldRow>
{renderTestAPIButton(value)}
<br />
{renderJSON(value?.data ?? '{}')}
</>
) : (
<>Must enable disableSanitizeHtml feature flag to access</>
);
};