Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/four-knives-wonder.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'grafana-google-sheets-datasource': minor
---

Add default spreadsheet ID to config editor
1 change: 1 addition & 0 deletions pkg/models/settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type DatasourceSettings struct {
TokenURI string `json:"tokenUri"`
AuthenticationType string `json:"authenticationType"`
PrivateKeyPath string `json:"privateKeyPath"`
DefaultSheetID string `json:"defaultSheetID"`

// Saved in secure JSON
PrivateKey string `json:"-"`
Expand Down
18 changes: 13 additions & 5 deletions src/DataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@ import {
DataSourceInstanceSettings,
ScopedVars,
SelectableValue,
CoreApp,
} from '@grafana/data';
import { DataSourceOptions } from '@grafana/google-sdk';
import { DataSourceWithBackend, getTemplateSrv, TemplateSrv } from '@grafana/runtime';
import { SheetsQuery, SheetsVariableQuery } from './types';
import { GoogleSheetsDataSourceOptions, SheetsQuery, SheetsVariableQuery } from './types';
import { Observable } from 'rxjs';
import { trackRequest } from 'tracking';
import { SheetsVariableSupport } from 'variables';

export class DataSource extends DataSourceWithBackend<SheetsQuery, DataSourceOptions> {
export class DataSource extends DataSourceWithBackend<SheetsQuery, GoogleSheetsDataSourceOptions> {
authType: string;
constructor(
instanceSettings: DataSourceInstanceSettings<DataSourceOptions>,
private instanceSettings: DataSourceInstanceSettings<GoogleSheetsDataSourceOptions>,
private readonly templateSrv: TemplateSrv = getTemplateSrv()
) {
super(instanceSettings);
Expand Down Expand Up @@ -63,8 +63,16 @@ export class DataSource extends DataSourceWithBackend<SheetsQuery, DataSourceOpt
async getSpreadSheets(): Promise<Array<SelectableValue<string>>> {
return this.getResource('spreadsheets').then(({ spreadsheets }) =>
spreadsheets
? Object.entries(spreadsheets).map(([value, label]) => ({ label, value }) as SelectableValue<string>)
? Object.entries(spreadsheets).map(([value, label]) => ({
label,
value,
description: value,
}) as SelectableValue<string>)
: []
);
}

getDefaultQuery(app: CoreApp): Partial<SheetsQuery> {
return { spreadsheet: this.instanceSettings.jsonData.defaultSheetID || '' };
}
}
75 changes: 71 additions & 4 deletions src/components/ConfigEditor.test.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,42 @@
import React from 'react';

import { render, screen, fireEvent } from '@testing-library/react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ConfigEditor } from './ConfigEditor';
import { DataSourceSettings } from '@grafana/data';
import { GoogleSheetsSecureJSONData } from '../types';
import { GoogleAuthType, DataSourceOptions } from '@grafana/google-sdk';

jest.mock('@grafana/plugin-ui', () => ({
DataSourceDescription: () => <div data-testid="data-source-description" />,
}));
jest.mock('@grafana/runtime', () => ({
getDataSourceSrv: () => ({
get: (_: string) =>
Promise.resolve({
getSpreadSheets: () =>
Promise.resolve([
{ label: 'label1', value: 'value1', description: 'value1' },
]),
}),
}),
}));

const dataSourceSettings: Partial<DataSourceSettings<DataSourceOptions, GoogleSheetsSecureJSONData>> = {
jsonData: {
authenticationType: GoogleAuthType.JWT,
},
secureJsonFields: {
jwt: true,
},
uid: 'test-uid',
};


describe('ConfigEditor', () => {
afterEach(() => {
jest.clearAllMocks();
});

it('should support old authType property', () => {
const onOptionsChange = jest.fn();
// Render component with old authType property
Expand Down Expand Up @@ -42,8 +75,6 @@ describe('ConfigEditor', () => {
expect(screen.getByPlaceholderText('Enter API key')).toHaveAttribute('value', 'configured');
});

//

it('should be backward compatible with JWT auth type', () => {
render(
<ConfigEditor
Expand All @@ -58,4 +89,40 @@ describe('ConfigEditor', () => {
// Check that the Private key input is configured
expect(screen.getByTestId('Private Key Input')).toHaveAttribute('value', 'configured');
});
it('should render default spreadsheet ID field', () => {
render(
<ConfigEditor
onOptionsChange={jest.fn()}
options={{ jsonData: { authenticationType: 'key' }, secureJsonFields: {} } as any}
/>
);
expect(screen.getByText('Default Spreadsheet ID')).toBeInTheDocument();
});

it('should update default spreadsheet after selecting it', async () => {
const onOptionsChange = jest.fn();
render(
<ConfigEditor
onOptionsChange={onOptionsChange}
options={dataSourceSettings as DataSourceSettings<DataSourceOptions, GoogleSheetsSecureJSONData>}
/>
);

const selectEl = screen.getByText('Select Spreadsheet ID');
expect(selectEl).toBeInTheDocument();

await userEvent.click(selectEl);
const spreadsheetOption = await screen.findByText('label1', {}, { timeout: 3000 });
await userEvent.click(spreadsheetOption);

await waitFor(() => {
expect(onOptionsChange).toHaveBeenCalledWith(
expect.objectContaining({
jsonData: expect.objectContaining({
defaultSheetID: 'value1',
}),
})
);
});
});
});
78 changes: 71 additions & 7 deletions src/components/ConfigEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
import { DataSourcePluginOptionsEditorProps, onUpdateDatasourceSecureJsonDataOption } from '@grafana/data';
import { AuthConfig, DataSourceOptions } from '@grafana/google-sdk';
import { Field, SecretInput, Divider } from '@grafana/ui';
import React from 'react';
import { GoogleSheetsAuth, GoogleSheetsSecureJSONData, googleSheetsAuthTypes } from '../types';
import {
DataSourcePluginOptionsEditorProps,
onUpdateDatasourceSecureJsonDataOption,
SelectableValue,
} from '@grafana/data';
import { AuthConfig } from '@grafana/google-sdk';
import { DataSourceDescription } from '@grafana/plugin-ui';
import { Field, SecretInput, SegmentAsync, Divider } from '@grafana/ui';
import React, { useState, useEffect } from 'react';
import { GoogleSheetsSecureJSONData, googleSheetsAuthTypes, GoogleSheetsAuth, GoogleSheetsDataSourceOptions } from '../types';
import { getBackwardCompatibleOptions } from '../utils';
import { ConfigurationHelp } from './ConfigurationHelp';
import { DataSourceDescription } from '@grafana/plugin-ui';
import { getDataSourceSrv } from '@grafana/runtime';
import { DataSource } from '../DataSource';

export type Props = DataSourcePluginOptionsEditorProps<DataSourceOptions, GoogleSheetsSecureJSONData>;
export type Props = DataSourcePluginOptionsEditorProps<GoogleSheetsDataSourceOptions, GoogleSheetsSecureJSONData>;

export function ConfigEditor(props: Props) {
const options = getBackwardCompatibleOptions(props.options);
const [selectedSheetOption, setSelectedSheetOption] = useState<SelectableValue<string> | string | undefined>(
options.jsonData.defaultSheetID
);

const apiKeyProps = {
isConfigured: Boolean(options.secureJsonFields.apiKey),
Expand All @@ -27,6 +36,36 @@ export function ConfigEditor(props: Props) {
onChange: onUpdateDatasourceSecureJsonDataOption(props, 'apiKey'),
};

const loadSheetIDs = async () => {
if (!options.uid) {
return [];
}
try {
const ds = (await getDataSourceSrv().get(options.uid)) as DataSource;
return ds.getSpreadSheets();
} catch {
return [];
}
};

useEffect(() => {
const currentValue = options.jsonData.defaultSheetID;
if (!currentValue || !options.uid) {
setSelectedSheetOption(currentValue);
return;
}
const updateSelectedOption = async () => {
try {
const ds = (await getDataSourceSrv().get(options.uid!)) as DataSource;
const sheetOptions = await ds.getSpreadSheets();
const matchingOption = sheetOptions.find((opt) => opt.value === currentValue);
setSelectedSheetOption(matchingOption || currentValue);
} catch {
setSelectedSheetOption(currentValue);
}
};
updateSelectedOption();
}, [options.jsonData.defaultSheetID, options.uid]);
return (
<>
<DataSourceDescription
Expand Down Expand Up @@ -59,6 +98,31 @@ export function ConfigEditor(props: Props) {
<SecretInput {...apiKeyProps} label="API key" width={40} />
</Field>
)}

<Divider />

<Field
label="Default Spreadsheet ID"
description="Optional spreadsheet ID to use as default when creating new queries"
>
<SegmentAsync
loadOptions={loadSheetIDs}
placeholder="Select Spreadsheet ID"
value={selectedSheetOption}
allowCustomValue={true}
onChange={(value) => {
const sheetId = typeof value === 'string' ? value : value?.value;
setSelectedSheetOption(value);
props.onOptionsChange({
...options,
jsonData: {
...options.jsonData,
defaultSheetID: sheetId,
},
});
}}
/>
</Field>
</>
);
}
60 changes: 57 additions & 3 deletions src/components/QueryEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { QueryEditorProps } from '@grafana/data';
import { QueryEditorProps, SelectableValue } from '@grafana/data';
import { DataSourceOptions } from '@grafana/google-sdk';
import { InlineFieldRow, InlineFormLabel, InlineSwitch, Input, LinkButton, Segment, SegmentAsync } from '@grafana/ui';
import React, { ChangeEvent, PureComponent } from 'react';
Expand All @@ -9,6 +9,25 @@ import { css } from '@emotion/css';

type Props = QueryEditorProps<DataSource, SheetsQuery, DataSourceOptions>;

type SelectedSheetOption = SelectableValue<string> | string | undefined;

function resolveSelectedSheetOption(
options: Array<SelectableValue<string>>,
spreadsheet?: string
): SelectableValue<string> | string | undefined {
if (!spreadsheet) {
return undefined;
}
return options.find((opt) => opt.value === spreadsheet) ?? spreadsheet;
}

function selectedSheetOptionKey(option: SelectedSheetOption): string | undefined {
if (option === undefined) {
return undefined;
}
return typeof option === 'string' ? option : option.value;
}

export function getGoogleSheetRangeInfoFromURL(url: string): Partial<SheetsQuery> {
let idx = url?.indexOf('/d/');
if (!idx) {
Expand Down Expand Up @@ -51,15 +70,40 @@ export const formatCacheTimeLabel = (s: number = defaultCacheDuration) => {
};

export class QueryEditor extends PureComponent<Props> {
state = {
selectedSheetOption: undefined as SelectedSheetOption,
};

componentDidMount() {
if (!this.props.query.hasOwnProperty('cacheDurationSeconds')) {
this.props.onChange({
...this.props.query,
cacheDurationSeconds: defaultCacheDuration, // um :(
});
}
this.updateSelectedSheetOption();
}

componentDidUpdate(prevProps: Props) {
if (prevProps.query.spreadsheet !== this.props.query.spreadsheet) {
this.updateSelectedSheetOption();
}
}

updateSelectedSheetOption = async () => {
const { query, datasource } = this.props;
if (!query.spreadsheet) {
this.setState({ selectedSheetOption: undefined });
return;
}
try {
const sheetOptions = await datasource.getSpreadSheets();
this.setState({ selectedSheetOption: resolveSelectedSheetOption(sheetOptions, query.spreadsheet) });
} catch {
this.setState({ selectedSheetOption: query.spreadsheet });
}
};

onRangeChange = (event: ChangeEvent<HTMLInputElement>) => {
this.props.onChange({
...this.props.query,
Expand All @@ -71,10 +115,12 @@ export class QueryEditor extends PureComponent<Props> {
const { query, onRunQuery, onChange } = this.props;

if (!item.value) {
this.setState({ selectedSheetOption: undefined });
return; // ignore delete?
}

const v = item.value;
this.setState({ selectedSheetOption: item });
// Check for pasted full URLs
if (/(.*)\/spreadsheets\/d\/(.*)/.test(v)) {
onChange({ ...query, ...getGoogleSheetRangeInfoFromURL(v) });
Expand Down Expand Up @@ -118,9 +164,17 @@ export class QueryEditor extends PureComponent<Props> {
Spreadsheet ID
</InlineFormLabel>
<SegmentAsync
loadOptions={() => datasource.getSpreadSheets()}
loadOptions={async () => {
const options = await datasource.getSpreadSheets();
const { query } = this.props;
const next = resolveSelectedSheetOption(options, query.spreadsheet);
if (selectedSheetOptionKey(this.state.selectedSheetOption) !== selectedSheetOptionKey(next)) {
this.setState({ selectedSheetOption: next });
}
return options;
}}
placeholder="Enter SpreadsheetID"
value={query.spreadsheet}
value={this.state.selectedSheetOption ?? query.spreadsheet}
allowCustomValue={true}
onChange={this.onSpreadsheetIDChange}
/>
Expand Down
6 changes: 5 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { DataQuery } from '@grafana/schema';
import { GoogleAuthType, GOOGLE_AUTH_TYPE_OPTIONS, DataSourceSecureJsonData } from '@grafana/google-sdk';
import { GoogleAuthType, GOOGLE_AUTH_TYPE_OPTIONS, DataSourceSecureJsonData, DataSourceOptions } from '@grafana/google-sdk';

export const GoogleSheetsAuth = {
...GoogleAuthType,
Expand All @@ -12,6 +12,10 @@ export interface GoogleSheetsSecureJSONData extends DataSourceSecureJsonData {
apiKey?: string;
}

export interface GoogleSheetsDataSourceOptions extends DataSourceOptions {
defaultSheetID?: string;
}

export interface CacheInfo {
hit: boolean;
count: number;
Expand Down
Loading