Skip to content

Add type argument for RouteHandlerContext #57588

@joshdover

Description

@joshdover

We currently only support "extending" the RouteHandlerContext by reopening the type:

declare module 'src/core/server' {
  interface RouteHandlerContext {
    myField: MyType;
  }
}

This has a few problems:

  • Depending on how a TS project is set up, this type extension can be present for plugins that it was not intended to be included on.
  • It's not very explicit.
  • It's not very obvious how or why it's done this way.

Instead, we could add a type argument to IRouter (and related types, like RouteHandler) for the RouteHandlerContext so plugins can explicitly specify which contexts they expect from their own context providers + any specified by their dependencies. Example:

import { MyDependencyContext } from '../../my_dependency/server';
import { RouteHandlerContext } from 'src/core/server';

interface MyRouteHandlerContext extends RouteHandlerContext {
  myDependency: MyDependencyContext;
  myContext: MyContext;
}

class Plugin {
  setup(core) {
    const router = core.http.createRouter<MyRouteHandlerContext>();
    router.get(
      { path: '/my-route', validate: false }
      async (context, req, res) => {
        context.myDependency.doThing(); // TS is happy!
        // ...
      }
    );
  }
}

Metadata

Metadata

Labels

Feature:New PlatformTeam:CorePlatform Core services: plugins, logging, config, saved objects, http, ES client, i18n, etc t//

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions