kibana/docs/developer/architecture/core/patterns-scoped-services.asciidoc
Christiane (Tina) Heiligers d29abdfa15
[DOCS] Adds user-facing docs for the new KP logging configuration (#94993)
Co-authored-by: Lisa Cawley <lcawley@elastic.co>
2021-03-30 07:54:15 -07:00

61 lines
2.4 KiB
Text

[[patterns]]
== Patterns
[[scoped-services]]
=== Scoped services
Whenever Kibana needs to get access to data saved in Elasticsearch, it
should perform a check whether an end-user has access to the data.
The Kibana Platform introduced a handler interface on the server-side to perform that association
internally. Core services, that require impersonation with an incoming
request, are exposed via `context` argument of
{kib-repo}blob/{branch}/docs/development/core/server/kibana-plugin-core-server.requesthandler.md[the
request handler interface.]
as
[source,js]
----
async function handler(context, req, res) {
const data = await context.core.elasticsearch.client.asCurrentUser('ping');
}
----
The
{kib-repo}blob/{branch}/docs/development/core/server/kibana-plugin-core-server.requesthandlercontext.md[request
handler context] exposes the following scoped *core* services:
* {kib-repo}blob/{branch}/docs/development/core/server/kibana-plugin-core-server.savedobjectsclient.md[`context.savedObjects.client`]
* {kib-repo}blob/{branch}/docs/development/core/server/kibana-plugin-core-server.iscopedclusterclient.md[`context.elasticsearch.client`]
* {kib-repo}blob/{branch}/docs/development/core/server/kibana-plugin-core-server.iuisettingsclient.md[`context.uiSettings.client`]
==== Declare a custom scoped service
Plugins can extend the handler context with a custom API that will be
available to the plugin itself and all dependent plugins. For example,
the plugin creates a custom Elasticsearch client and wants to use it via
the request handler context:
[source,typescript]
----
import type { CoreSetup, RequestHandlerContext, IScopedClusterClient } from 'kibana/server';
interface MyRequestHandlerContext extends RequestHandlerContext {
myPlugin: {
client: IScopedClusterClient;
};
}
class MyPlugin {
setup(core: CoreSetup) {
const client = core.elasticsearch.createClient('myClient');
core.http.registerRouteHandlerContext<MyRequestHandlerContext, 'myPlugin'>('myPlugin', (context, req, res) => {
return { client: client.asScoped(req) };
});
const router = core.http.createRouter<MyRequestHandlerContext>();
router.get(
{ path: '/api/my-plugin/', validate: … },
async (context, req, res) => {
// context type is inferred as MyPluginContext
const data = await context.myPlugin.client.asCurrentUser('endpoint');
}
);
}
----