Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Data Source option for reset button #296

Merged
merged 4 commits into from
Nov 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
- Update to Grafana 10.2.1 (#292)
- Update ESLint configuration (#294)
- Add Autosize Code Editor (#295)
- Add Data Source option for Reset button (#296)

### Bugfixes

Expand Down
157 changes: 157 additions & 0 deletions src/components/FormPanel/FormPanel.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1461,6 +1461,163 @@ describe('Panel', () => {

jest.mocked(getAppEvents).mockClear();
});

it('Should run reset datasource request', async () => {
/**
* Render
*/
jest.mocked(fetch).mockImplementationOnce(
() =>
Promise.resolve({
ok: true,
json: jest.fn(() =>
Promise.resolve({
test: '123',
number: 123,
})
),
}) as any
);

const datasourceRequestMock = jest.fn(() =>
Promise.resolve({
message: 'hello',
ok: true,
})
) as any;
jest.mocked(useDatasourceRequest).mockImplementation(() => datasourceRequestMock);

const { rerender } = await act(async () =>
render(
getComponent({
options: {
elements: [
{ ...FormElementDefault, id: 'test', value: '123' },
{ type: FormElementType.NUMBER, id: 'number', value: 123 },
],
},
})
)
);
/**
* Trigger element updates
*/
await act(async () =>
rerender(
getComponent({
options: {
elements: [
{ ...FormElementDefault, id: 'test', value: '123' },
{ type: FormElementType.NUMBER, id: 'number', value: 111 },
{ type: FormElementType.DISABLED, id: 'disabled', value: '222' },
],
resetAction: {
datasource: 'abc',
mode: ResetActionMode.DATASOURCE,
payloadMode: PayloadMode.CUSTOM,
getPayload: `return { key1: 'value' }`,
},
},
})
)
);

/**
* Check if Reset can be run
*/
expect(selectors.buttonReset()).toBeInTheDocument();
expect(selectors.buttonReset()).not.toBeDisabled();

/**
* Run reset request
*/
await act(async () => {
fireEvent.click(selectors.buttonReset());
});

expect(datasourceRequestMock).toHaveBeenCalledWith({
datasource: 'abc',
query: {
key1: 'value',
},
replaceVariables: expect.any(Function),
});
});

it('Should show reset datasource request error', async () => {
/**
* Render
*/
jest.mocked(fetch).mockImplementationOnce(
() =>
Promise.resolve({
ok: true,
json: jest.fn(() =>
Promise.resolve({
test: '123',
number: 123,
})
),
}) as any
);

const datasourceRequestMock = jest.fn(() =>
Promise.reject({
message: 'hello',
})
);
jest.mocked(useDatasourceRequest).mockImplementation(() => datasourceRequestMock);

const { rerender } = await act(async () =>
render(
getComponent({
options: {
elements: [
{ ...FormElementDefault, id: 'test', value: '123' },
{ type: FormElementType.NUMBER, id: 'number', value: 123 },
],
},
})
)
);
/**
* Trigger element updates
*/
await act(async () =>
rerender(
getComponent({
options: {
elements: [
{ ...FormElementDefault, id: 'test', value: '123' },
{ type: FormElementType.NUMBER, id: 'number', value: 111 },
{ type: FormElementType.DISABLED, id: 'disabled', value: '222' },
],
resetAction: {
datasource: 'abc',
mode: ResetActionMode.DATASOURCE,
payloadMode: PayloadMode.CUSTOM,
getPayload: `return { key1: 'value' }`,
},
},
})
)
);

/**
* Check if Reset can be run
*/
expect(selectors.buttonReset()).toBeInTheDocument();
expect(selectors.buttonReset()).not.toBeDisabled();

/**
* Run reset request
*/
await act(async () => {
fireEvent.click(selectors.buttonReset());
});

await waitFor(() => expect(selectors.errorMessage()).toBeInTheDocument());
});
});

describe('Confirm changes', () => {
Expand Down
78 changes: 77 additions & 1 deletion src/components/FormPanel/FormPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,11 @@ export const FormPanel: React.FC<Props> = ({
* Reset Request
*/
const resetRequest = async () => {
/**
* Clear Error
*/
setError('');

if (options.resetAction.mode === ResetActionMode.INITIAL) {
/**
* Use Initial Request
Expand All @@ -467,15 +472,86 @@ export const FormPanel: React.FC<Props> = ({
return;
}

if (options.resetAction.mode === ResetActionMode.CUSTOM) {
/**
* Loading
*/
setLoading(LoadingMode.RESET);

/**
* Execute Custom Code and reset Loading
*/
await executeCustomCode({ code: options.resetAction.code, initial });
setLoading(LoadingMode.NONE);
}

/**
* Loading
*/
setLoading(LoadingMode.RESET);

if (!options.resetAction.datasource) {
/**
* Show No Data Source Error and Reset Loading
*/
setError('Please select Data Source for Reset Request.');
setLoading(LoadingMode.NONE);

return;
}

/**
* Set payload
*/
const payload = GetPayloadForRequest({
request: {
datasource: options.resetAction.datasource,
payloadMode: PayloadMode.CUSTOM,
method: RequestMethod.NONE,
url: '',
header: [],
getPayload: options.resetAction.getPayload,
contentType: ContentType.PLAIN,
code: options.resetAction.code,
highlight: false,
highlightColor: '',
confirm: false,
updatedOnly: false,
},
elements,
initial,
});

/**
* Datasource query
*/
const response: FetchResponse | null = await datasourceRequest({
query: payload,
datasource: options.resetAction.datasource,
replaceVariables,
}).catch((error: DataQueryError) => {
setError(JSON.stringify(error));
return null;
});

let currentElements = elements;
if (response && response.ok) {
/**
* Change Elements With Data Source Values
*/
const queryResponse = toDataQueryResponse(response as FetchResponse);
currentElements = getElementsWithFieldValues(queryResponse.data, RequestMethod.DATASOURCE);

/**
* Update Elements
*/
onChangeElements(currentElements);
}

/**
* Execute Custom Code and reset Loading
*/
await executeCustomCode({ code: options.resetAction.code, initial });
await executeCustomCode({ code: options.resetAction.code, initial, response, currentElements });
setLoading(LoadingMode.NONE);
};

Expand Down
4 changes: 3 additions & 1 deletion src/constants/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,12 +110,14 @@ export const PayloadModeOptions = [
export const enum ResetActionMode {
INITIAL = 'initial',
CUSTOM = 'custom',
DATASOURCE = 'datasource',
}

/**
* Reset Action Options
*/
export const ResetActionOptions = [
{ label: 'Custom Code', value: ResetActionMode.CUSTOM },
{ label: 'Initial request', value: ResetActionMode.INITIAL },
{ label: 'Initial Request', value: ResetActionMode.INITIAL },
{ label: 'Data Source', value: ResetActionMode.DATASOURCE },
];
17 changes: 17 additions & 0 deletions src/module.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,5 +266,22 @@ describe('plugin', () => {

expect(shownOptionsPaths).toEqual(expect.arrayContaining(['resetAction.code']));
});

it('Should show reset payload if reset action is data source', () => {
const shownOptionsPaths: string[] = [];

builder.addCustomEditor.mockImplementation(
addInputImplementation(
{
reset: { variant: ButtonVariant.CUSTOM } as any,
resetAction: { mode: ResetActionMode.DATASOURCE, datasource: '123' } as any,
},
shownOptionsPaths
)
);
plugin['optionsSupplier'](builder);

expect(shownOptionsPaths).toEqual(expect.arrayContaining(['resetAction.getPayload']));
});
});
});
42 changes: 40 additions & 2 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -593,7 +593,7 @@ export const plugin = new PanelPlugin<PanelOptions>(FormPanel).setNoPadding().se
.addRadio({
path: 'resetAction.mode',
name: 'Reset Action',
category: ['Reset request'],
category: ['Reset Request'],
description: 'What action should be called by clicking on reset button.',
settings: {
options: ResetActionOptions,
Expand All @@ -607,15 +607,53 @@ export const plugin = new PanelPlugin<PanelOptions>(FormPanel).setNoPadding().se
name: 'Custom Code',
description: 'Custom code to execute reset request.',
editor: CustomCodeEditor,
category: ['Reset request'],
category: ['Reset Request'],
settings: {
language: CodeLanguage.JAVASCRIPT,
},
defaultValue: CodeResetDefault,
showIf: (config) =>
config.reset.variant !== ButtonVariant.HIDDEN && config.resetAction.mode === ResetActionMode.CUSTOM,
})
.addCustomEditor({
id: 'resetAction.datasource',
path: 'resetAction.datasource',
name: 'Data Source',
category: ['Reset Request'],
editor: DatasourceEditor,
showIf: (config) => config.resetAction.mode === ResetActionMode.DATASOURCE,
})
.addCustomEditor({
id: 'resetAction.code',
path: 'resetAction.code',
name: 'Custom Code',
description: 'Custom code to execute after reset request.',
editor: CustomCodeEditor,
category: ['Reset Request'],
settings: {
language: CodeLanguage.JAVASCRIPT,
},
defaultValue: CodeUpdateDefault,
showIf: (config) => config.resetAction.mode === ResetActionMode.DATASOURCE,
});

/**
* Reset Request Payload
*/
builder.addCustomEditor({
id: 'resetAction.getPayload',
path: 'resetAction.getPayload',
name: 'Create Payload',
description: 'Custom code to create payload for the reset data source request.',
editor: CustomCodeEditor,
category: ['Reset Request Payload'],
settings: {
language: CodeLanguage.JAVASCRIPT,
},
defaultValue: PayloadInitialDefault,
showIf: (config) => config.resetAction.mode === ResetActionMode.DATASOURCE && !!config.resetAction.datasource,
});

/**
* Save Defaults Button
*/
Expand Down
14 changes: 14 additions & 0 deletions src/types/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,4 +107,18 @@ export interface ResetAction {
* @type {string}
*/
code: string;

/**
* Data Source
*
* @type {string}
*/
datasource: string;

/**
* Get Payload
*
* @type {string}
*/
getPayload: string;
}
Loading