Skip to content

Opensearch dashboards.requesthandler

Home > opensearch-dashboards > RequestHandler

RequestHandler type

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

Signature:

export declare type RequestHandler<P = unknown, Q = unknown, B = unknown, Method extends RouteMethod = any, ResponseFactory extends OpenSearchDashboardsResponseFactory = OpenSearchDashboardsResponseFactory> = (context: RequestHandlerContext, request: OpenSearchDashboardsRequest<P, Q, B, Method>, response: ResponseFactory) => IOpenSearchDashboardsResponse<any> | Promise<IOpenSearchDashboardsResponse<any>>;

References: RouteMethod, OpenSearchDashboardsResponseFactory, RequestHandlerContext, OpenSearchDashboardsRequest, IOpenSearchDashboardsResponse

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);
  }
);