Integrations
Accessing the AppRouter
In some circumstances ,for example end-to-end tests or integrating with other trpc
plugins, you may want to get a reference to the generated appRouter object. In end-to-end tests, you can then run queries using the appRouter object directly without using any HTTP listeners.
You can access the generated appRouter using the AppRouterHost
class:
const { appRouter } = app.get(AppRouterHost);
You must call the AppRouterHost.appRouter
getter after the application has been initialized (after the onModuleInit
hook has been triggered by either the app.listen()
or app.init()
method).
With the runtime appRouter object, you can integrate with virtually any trpc-specific library, this includes trpc-panel (opens in a new tab), trpc-openapi (opens in a new tab), trpc-playground (opens in a new tab) and more.
Integrating with trpc-panel
Here is a short example of how to integrate trpc-panel (opens in a new tab), while this is a specific integration, the techniques used here can be applied to any of the trpc-specific libraries you wish to include.
If you still run into issues, please open a new issue (opens in a new tab) or contact us via Discord.
Installation
To install trpc-panel
with your preferred package manager, you can use any of the following commands:
npm install trpc-panel
Creating the Panel Controller
As per the trpc-panel
docs (opens in a new tab) we need to serve the panel, using the renderTrpcPanel
method for every method on route /panel
.
import { All, Controller, Inject, OnModuleInit } from '@nestjs/common';
import { renderTrpcPanel } from 'trpc-panel';
import { AnyRouter } from '@trpc/server';
import { AppRouterHost } from 'nestjs-trpc';
@Controller()
export class TrpcPanelController implements OnModuleInit {
private appRouter!: AnyRouter;
constructor(
@Inject(AppRouterHost) private readonly appRouterHost: AppRouterHost,
) {}
onModuleInit() {
this.appRouter = this.appRouterHost.appRouter;
}
@All('/panel')
panel(): string {
return renderTrpcPanel(this.appRouter, {
url: 'http://localhost:8080/trpc',
});
}
}
As you can see in the example above, we are using onModuleInit
lifecycle method to make sure the appRouter is initialized and available.
Register the Controller
In order to apply the new Controller routes, we need to register it in the app.module.ts
file.
@Module({
imports: [
TRPCModule.forRoot({
autoSchemaFile: './src/@generated',
context: AppContext,
}),
],
controllers: [TrpcPanelController],
providers: [],
})
export class AppModule {}
Once you've registered the controller, start your NestJS application. You can then access the tRPC panel at https://localhost:8080/panel (opens in a new tab).