跳到主要内容

为你的插件添加用户存储

用户存储允许你的 Grafana 插件在 Grafana 数据库中存储用户特定数据。这些数据仅对单个用户可访问。但是,请记住数据未加密,不应用于存储敏感信息。用户存储的典型用例包括保存用户偏好设置或配置。

重要
  • 此功能在 Grafana 11.5 及更高版本中可用。
  • 它需要启用 userStorageAPI 功能标志。
  • 如果插件使用此功能但在 Grafana 实例中未启用,则会改为使用浏览器 localStorage 作为存储机制。

示例:向查询编辑器添加用户存储

在此示例中,我们将通过集成用户存储来增强 QueryEditor 组件。它有一个 Select 字段,你可以在其中选择预期的查询结果类型。目标是记住用户的首选查询类型(例如,“时间序列”或“表格”),并在下次打开查询编辑器时将其用作默认值。

import React, { ReactElement, useEffect } from 'react';
import { InlineFieldRow, InlineField, Select } from '@grafana/ui';
import { QueryEditorProps, SelectableValue } from '@grafana/data';
import { usePluginUserStorage } from '@grafana/runtime';

import { DataSource } from 'datasource';
import { MyDataSourceOptions, MyQuery } from 'types';

type Props = QueryEditorProps<DataSource, MyQuery, MyDataSourceOptions>;

export function QueryEditor(props: Props): ReactElement {
const { query, onChange } = props;
const queryTypes = [
{
label: 'Timeseries',
value: 'timeseries',
},
{
label: 'Table',
value: 'table',
},
];
const storage = usePluginUserStorage();
useEffect(() => {
// Load the default query type from user storage
storage.getItem('queryType').then((value) => {
if (value && !query.queryType) {
onChange({
...query,
queryType: value,
});
}
});
}, []);

const onChangeQueryType = (type: SelectableValue<string>) => {
if (type.value) {
onChange({
...query,
queryType: type.value,
});
// Save the query type to user storage to be used by default for the next time
storage.setItem('queryType', type.value);
}
};

return (
<>
<InlineFieldRow>
<InlineField label="Query type" grow>
<Select options={queryTypes} onChange={onChangeQueryType} value={{ value: query.queryType }} />
</InlineField>
</InlineFieldRow>
</>
);
}