[Dashboards] Provide a method for fetching dashboards on the Dashboard server plugin contract (#209678)

Fixes #209695

## Summary

Adds a method from content management for exposing a server-side
Dashboard CRUD client.

Consumers who want to search, retrieve, or modify Dashboards from a
server plugin find themselves using the Saved Object client. This means
they need to handle JSON parse/stringify and reference handling
themselves. We could expose a CRUD functionality from content management
on the Dashboard server plugin contract to avoid re-creating all of this
boilerplate handling.

Commit c53f47d72a shows a crude
demonstration of how a plugin can use the methods available on the
Dashboard server plugin with a request to retrieve a list of dashboards.
You can test this in the Dev Tools:

```
GET kbn:/api/search_dashboards?spaces=*
```

This will use the Search method from content management to return a list
of dashboards across all spaces.

To allow the Search method to return all fields in the Dashboard, I
needed to remove the default fields. I updated all current uses of the
search method to specify the necessary fields. See
618e025210.


### Checklist

Check the PR satisfies following conditions. 

Reviewers should verify this PR satisfies this list as well.

- [x] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/src/platform/packages/shared/kbn-i18n/README.md)
- [x]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [x] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [x] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [x] This was checked for breaking HTTP API changes, and any breaking
changes have been approved by the breaking-change committee. The
`release_note:breaking` label should be applied in these situations.
- [x] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [x] The PR description includes the appropriate Release Notes section,
and the correct `release_note:*` label is applied per the
[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

### Identify risks

Does this PR introduce any risks? For example, consider risks like hard
to test bugs, performance regression, potential of data loss.

Describe the risk, its severity, and mitigation for each identified
risk. Invite stakeholders and evaluate how to proceed before merging.

- [ ] [See some risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)
- [ ] ...
This commit is contained in:
Nick Peihl 2025-02-28 10:05:04 -05:00 committed by GitHub
parent ab46ddeef2
commit 08c4338a25
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 67 additions and 6 deletions

View file

@ -217,6 +217,7 @@ export const useDashboardListingTable = ({
options: {
// include only tags references in the response to save bandwidth
includeReferences: ['tag'],
fields: ['title', 'description', 'timeRestore'],
},
})
.then(({ total, hits }) => {

View file

@ -237,7 +237,15 @@ export function registerAPIRoutes({
let result;
try {
// TODO add filtering
({ result } = await client.search({ cursor: page.toString(), limit }));
({ result } = await client.search(
{
cursor: page.toString(),
limit,
},
{
fields: ['title', 'description', 'timeRestore'],
}
));
} catch (e) {
if (e.isBoom && e.output.statusCode === 403) {
return res.forbidden();

View file

@ -40,11 +40,12 @@ const searchArgsToSOFindOptions = (
return {
type: DASHBOARD_SAVED_OBJECT_TYPE,
searchFields: options?.onlyTitle ? ['title'] : ['title^3', 'description'],
fields: options?.fields ?? ['title', 'description', 'timeRestore'],
fields: options?.fields,
search: query.text,
perPage: query.limit,
page: query.cursor ? +query.cursor : undefined,
defaultSearchOperator: 'AND',
namespaces: options?.spaces,
...tagsToFindOptions(query.tags),
};
};

View file

@ -456,6 +456,14 @@ export const dashboardSearchOptionsSchema = schema.maybe(
kuery: schema.maybe(schema.string()),
cursor: schema.maybe(schema.number()),
limit: schema.maybe(schema.number()),
spaces: schema.maybe(
schema.arrayOf(schema.string(), {
meta: {
description:
'An array of spaces to search or "*" to search all spaces. Defaults to the current space if not specified.',
},
})
),
},
{ unknowns: 'forbid' }
)

View file

@ -47,6 +47,7 @@ interface StartDeps {
export class DashboardPlugin
implements Plugin<DashboardPluginSetup, DashboardPluginStart, SetupDeps, StartDeps>
{
private contentClient?: ReturnType<ContentManagementServerSetup['register']>['contentClient'];
private readonly logger: Logger;
constructor(private initializerContext: PluginInitializerContext) {
@ -64,7 +65,7 @@ export class DashboardPlugin
})
);
plugins.contentManagement.register({
const { contentClient } = plugins.contentManagement.register({
id: CONTENT_ID,
storage: new DashboardStorage({
throwOnResultValidationError: this.initializerContext.env.mode.dev,
@ -74,6 +75,7 @@ export class DashboardPlugin
latest: LATEST_VERSION,
},
});
this.contentClient = contentClient;
plugins.contentManagement.favorites.registerFavoriteType('dashboard');
@ -136,7 +138,9 @@ export class DashboardPlugin
});
}
return {};
return {
contentClient: this.contentClient,
};
}
public stop() {}

View file

@ -7,7 +7,46 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import { ContentManagementServerSetup } from '@kbn/content-management-plugin/server';
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface DashboardPluginSetup {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface DashboardPluginStart {}
export interface DashboardPluginStart {
/**
* Use contentClient.getForRequest to get a scoped client to perform CRUD and search operations for dashboards using the methods available in the {@link DashboardStorage} class.
*
* @example
* Get a dashboard client for the current request
* ```ts
* // dashboardClient is scoped to the current user
* // specifying the version is recommended to return a consistent result
* const dashboardClient = plugins.dashboard.contentClient.getForRequest({ requestHandlerContext, request, version: 3 });
*
* const { search, create, update, delete: deleteDashboard } = dashboardClient;
* ```
*
* @example
* Search using {@link DashboardStorage#search}
* ```ts
* const dashboardList = await search({ text: 'my dashboard' }, { spaces: ['default'] } });
* ```
* @example
* Create a new dashboard using {@link DashboardCreateIn}
* ```ts
* const newDashboard = await create({ attributes: { title: 'My Dashboard' } });
* ```
*
* @example
* Update an existing dashboard using {@link DashboardUpdateIn}
* ```ts
* const updatedDashboard = await update({ id: 'dashboard-id', attributes: { title: 'My Updated Dashboard' } });
* ```
*
* @example
* Delete an existing dashboard using {@link DashboardDeleteIn}
* ```ts
* deleteDashboard({ id: 'dashboard-id' });
* ```
*/
contentClient?: ReturnType<ContentManagementServerSetup['register']>['contentClient'];
}