kibana/docs/development/core/server/kibana-plugin-server.requesthandler.md
Alejandro Fernández Haro f3f1bd2ec6
[NP] Allow custom validations in HTTP Routes apart from @kbn/config-schema (#51919) (#53714)
* [NP] Allow custom validations in HTTP Routes apart from @kbn/config-schema

* API docs

* Allow validate function in the route handler (run-code validation)

* Prefix RouteXXX + Params and Body Validation Aliases

* Fix test broken by lodash

* Update API docs

* Add default types for simpler manual declaration

* Add run-time validation of the RouteValidateSpec

* Expose RouteValidationError instead of SchemaTypeError

* RouteValidator as a class to match config-schema interface

* Test for not-inline handler (need to check IRouter for #47047)

* Add preValidation of the input for a safer custom validation

* Better types for RouteHandlers

* [NP] Move route validation to RouteValidator wrapper

* Use the class only internally but maintain the same API

* Fix types

* Ensure RouteValidator instance in KibanaRequest.from

* Fix validator.tests (Buffer.from instead of new Buffer)

* Default precheck should allow null values

* Also allow undefined in preChecks

* MR feedback fixes

* Provide RouteValidationResolver to the validation function

* Add functional tests

* Fix new functional tests

* Fix validator additional test

* Fix test with new resolver

* Remove unused import

* Rename ValidationResolver to ValidationResultFactory and change the interface to look more like the KibanaResponseFactory

Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com>

Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com>
2019-12-21 00:02:35 +00:00

1.5 KiB

Home > kibana-plugin-server > RequestHandler

RequestHandler type

A function executed when route path matched requested resource path. Request handler is expected to return a result of one of KibanaResponseFactory functions.

Signature:

export declare type RequestHandler<P = unknown, Q = unknown, B = unknown, Method extends RouteMethod = any> = (context: RequestHandlerContext, request: KibanaRequest<P, Q, B, Method>, response: KibanaResponseFactory) => IKibanaResponse<any> | Promise<IKibanaResponse<any>>;

Example

const router = httpSetup.createRouter();
// creates a route handler for GET request on 'my-app/path/{id}' path
router.get(
  {
    path: 'path/{id}',
    // defines a validation schema for a named segment of the route path
    validate: {
      params: schema.object({
        id: schema.string(),
      }),
    },
  },
  // function to execute to create a responses
  async (context, request, response) => {
    const data = await context.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
    return response.ok(data);
  }
);