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

Http server route handler implementation #41894

Merged
merged 17 commits into from
Jul 31, 2019

Conversation

mshustov
Copy link
Contributor

@mshustov mshustov commented Jul 24, 2019

Summary

initial implementation of #39767
closes #33779

Extends ResponseFactory functionality to configure response payload, status and headers.

Checklist

Use strikethroughs to remove checklist items you don't feel are applicable to this PR.

For maintainers

Dev docs

Kibana HTTP Service in the New platform provides own abstraction for work with HTTP stack.
Plugins don't have direct access to hapi server and its primitives anymore. Moreover,
plugins shouldn't rely on the fact that HTTP Service uses one or another library under the hood.
This gives the platform flexibility to upgrade or changing our internal HTTP stack without breaking plugins.
If the HTTP Service lacks functionality you need, we are happy to discuss and support your needs.

To handle an incoming request in your plugin you should:

  • Create a Router instance. Router is already configured to use plugin-id to prefix path segment for your routes.
const router = httpSetup.createRouter();
  • Use @kbn/config-schema package to create a schema to validate the request params, query, and body. Every incoming request will be validated against the created schema. If validation failed, the request is rejected with 400 status and Bad request error without calling the route's handler.
    To opt out of validating the request, specify false.
import { schema, TypeOf } from '@kbn/config-schema';
const validate = {
  params: schema.object({
    id: schema.string(),
  }),
};
  • Declare a function to respond to incoming request.
    The function will receive:
    1.context runtime context providing access to Kibana API, specific for a route handler.
    2.request object containing request details: url, headers, matched route, as well as validated params, query, body.
    3.response object instructing HTTP server to create HTTP response with information sent back to the client as the response body, headers, and HTTP status.
    Unlike, hapi route handler in the Legacy platform, any exception raised during the handler call will generate 500 Server error response and log error details for further investigation. See below for returning custom error responses.
const handler = async (context: RequestHandlerContext, request: KibanaRequest, response: ResponseFactory) => {
  const data = await findObject(request.params.id);
  // creates a command to respond with 'not found' error
  if (!data) return response.notFound();
  // creates a command to send found data to the client and set response headers
  return response.ok({
    body: data,
    headers: {
      'content-type': 'application/json'
    }
  });
}
  • Register route handler for GET request to 'my-app/path/{id}' path
import { schema, TypeOf } from '@kbn/config-schema';
const router = httpSetup.createRouter();

const validate = {
  params: schema.object({
    id: schema.string(),
  }),
};

router.get({
  path: 'path/{id}',
  validate
},
async (context, request, response) => {
  const data = await findObject(request.params.id);
  if (!data) return response.notFound();
  return response.ok({
    body: data,
    headers: {
      'content-type': 'application/json'
    }
  });
});

@mshustov mshustov added Feature:New Platform release_note:skip Skip the PR/issue when compiling release notes Team:Core Core services & architecture: plugins, logging, config, saved objects, http, ES client, i18n, etc v7.4.0 labels Jul 24, 2019
@elasticmachine
Copy link
Contributor

Pinging @elastic/kibana-platform

@elasticmachine
Copy link
Contributor

💔 Build Failed

@mshustov
Copy link
Contributor Author

retest

@elasticmachine
Copy link
Contributor

💔 Build Failed

@elasticmachine
Copy link
Contributor

💚 Build Succeeded

.expect(200);

expect(result.text).toBe('abc');
expect(result.header['transfer-encoding']).toBe('chunked');
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: some headers are set by hapi

@mshustov mshustov marked this pull request as ready for review July 25, 2019 13:31
@mshustov mshustov requested a review from a team as a code owner July 25, 2019 13:31
@mshustov mshustov added release_note:plugin_api_changes Contains a Plugin API changes section for the breaking plugin API changes section. and removed release_note:skip Skip the PR/issue when compiling release notes labels Jul 25, 2019
@elasticmachine
Copy link
Contributor

💔 Build Failed

@elasticmachine
Copy link
Contributor

💔 Build Failed

@elasticmachine
Copy link
Contributor

💚 Build Succeeded

@mshustov
Copy link
Contributor Author

@joshdover @rudolf updated

@elasticmachine
Copy link
Contributor

💚 Build Succeeded

@mshustov mshustov mentioned this pull request Jul 30, 2019
@mshustov mshustov merged commit 38231c6 into elastic:master Jul 31, 2019
@mshustov mshustov deleted the http-server-route-handler branch July 31, 2019 07:34
mshustov added a commit to mshustov/kibana that referenced this pull request Jul 31, 2019
* add response error

* add hapi response adapter

* add router handler

* add tests

* add comments, update docs

* update tests

* cleanup tests

* address @joshdover comments

* move tests under integration test cathegory

* update docs

* get rid of KibanResponseError class

* update docs
mshustov added a commit that referenced this pull request Jul 31, 2019
* add response error

* add hapi response adapter

* add router handler

* add tests

* add comments, update docs

* update tests

* cleanup tests

* address @joshdover comments

* move tests under integration test cathegory

* update docs

* get rid of KibanResponseError class

* update docs
jloleysens added a commit to jloleysens/kibana that referenced this pull request Jul 31, 2019
…-or-edit-existing-rollup-job

* 'master' of github.com:elastic/kibana: (114 commits)
  [ML] Fixing empty index pattern list (elastic#42299)
  [Markdown] Shim new platform - cleanup plugin (elastic#41760)
  [Code] Enable hierarchicalDocumentSymbolSupport for java language server (elastic#42233)
  Add New Platform mocks for data plugin (elastic#42261)
  Http server route handler implementation (elastic#41894)
  [SR] Allow custom index pattern to be used instead of selectable list when choosing indices to restore (elastic#41534)
  [Code] distributed Code abstraction (elastic#41374)
  [SIEM] Sets page titles to the current page you are on  (elastic#42157)
  Saved Objects export API stable type order (elastic#42310)
  cancellation of interpreter execution (elastic#40238)
  [SIEM] Fixes a crash when Machine Learning influencers is an undefined value (elastic#42198)
  Changed the job to work with a dedicated index (elastic#42297)
  FTR: fix testSubjects.missingOrFail (elastic#42290)
  Increase retry timeout to prevent flaky tests (elastic#42291)
  Spaces - make space a hidden saved object type (elastic#41688)
  Allow applications to register feature privileges which are excluded from the base privileges (elastic#41300)
  Disable flaky log column reorder test (elastic#42285)
  Fixing add element in element reducer (elastic#42276)
  Fix infinite loop (elastic#42228)
  [Maps][File upload] Remove geojson deep clone logic, handle on maps side (elastic#41835)
  ...
@elasticmachine
Copy link
Contributor

💚 Build Succeeded

@jfsiii jfsiii mentioned this pull request Aug 14, 2019
5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backported Feature:New Platform release_note:plugin_api_changes Contains a Plugin API changes section for the breaking plugin API changes section. Team:Core Core services & architecture: plugins, logging, config, saved objects, http, ES client, i18n, etc v7.4.0
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[New platform] Extend Route handler capabilities
4 participants