Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion docs/pages/docs/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import JsonLd from '../../components/JsonLd';

This document will guide you through the installation and setting up of **NestJS tRPC** in your nestjs project.

**NestJS tRPC** supports NestJS 9 through 12 on both the Express and Fastify adapters, and requires tRPC v11 with Zod 3 or Zod 4.
**NestJS tRPC** supports NestJS 9 through 12 on the Express and Fastify adapters, as well as the Node adapter (`@nestjs/platform-node`, NestJS 12.4+), and requires tRPC v11 with Zod 3 or Zod 4.

<Callout type={'warning'} emoji={'⚠️'}>
If you don't have a NestJS project setup yet, please visit our
Expand Down
71 changes: 70 additions & 1 deletion packages/nestjs-trpc/lib/__tests__/trpc.driver.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { HttpAdapterHost, ModuleRef } from '@nestjs/core';
import { TRPCDriver } from '../trpc.driver';
import { TRPCFactory } from '../factories/trpc.factory';
import { AppRouterHost } from '../app-router.host';
import { ExpressDriver, FastifyDriver } from '../drivers';
import { ExpressDriver, FastifyDriver, NodeDriver } from '../drivers';
import { TRPC_LOGGER } from '../trpc.constants';
import { TRPCModuleOptions } from '../interfaces';

Expand All @@ -17,6 +17,15 @@ function createMockExpressApp() {
return app;
}

function createMockNodeApp() {
const app: any = function () {};
app.get = jest.fn();
app.post = jest.fn();
app.use = jest.fn();
app.handle = jest.fn();
return app;
}

describe('TRPCDriver', () => {
let trpcDriver: TRPCDriver;
let moduleRef: ModuleRef;
Expand All @@ -42,6 +51,10 @@ describe('TRPCDriver', () => {
start: jest.fn().mockResolvedValue(undefined),
};

const mockNodeDriver = {
start: jest.fn().mockResolvedValue(undefined),
};

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
Expand Down Expand Up @@ -70,6 +83,10 @@ describe('TRPCDriver', () => {
provide: FastifyDriver,
useValue: mockFastifyDriver,
},
{
provide: NodeDriver,
useValue: mockNodeDriver,
},
],
}).compile();

Expand Down Expand Up @@ -199,6 +216,58 @@ describe('TRPCDriver', () => {
});
});

describe('http adapter platforms', () => {
afterEach(() => {
mockHttpAdapterHost.httpAdapter.getType.mockReturnValue('express');
mockHttpAdapterHost.httpAdapter.getInstance.mockReturnValue(
mockExpressApp,
);
});

it('starts the node driver for the node platform', async () => {
const mockNodeApp = createMockNodeApp();
mockHttpAdapterHost.httpAdapter.getType.mockReturnValue('node');
mockHttpAdapterHost.httpAdapter.getInstance.mockReturnValue(mockNodeApp);

const options: TRPCModuleOptions = { basePath: '/api/trpc' };

await trpcDriver.start(options);

expect(mockNodeDriver.start).toHaveBeenCalledWith(
options,
mockNodeApp,
expect.anything(),
null,
null,
{},
);
expect(mockExpressDriver.start).not.toHaveBeenCalled();
expect(mockFastifyDriver.start).not.toHaveBeenCalled();
});

it('throws for an unknown platform', async () => {
mockHttpAdapterHost.httpAdapter.getType.mockReturnValue('koa');
mockHttpAdapterHost.httpAdapter.getInstance.mockReturnValue({});

await expect(trpcDriver.start({})).rejects.toThrow(
'Unsupported http adapter: koa',
);
});

it('throws when the node platform instance does not look like a node router', async () => {
mockHttpAdapterHost.httpAdapter.getType.mockReturnValue('node');
mockHttpAdapterHost.httpAdapter.getInstance.mockReturnValue({
use: jest.fn(),
});

await expect(trpcDriver.start({})).rejects.toThrow(
'Unsupported http adapter: node',
);
expect(mockNodeDriver.start).not.toHaveBeenCalled();
expect(mockExpressDriver.start).not.toHaveBeenCalled();
});
});

describe('trpc options', () => {
it('passes adapter options to the http driver with reserved keys stripped', async () => {
const options: TRPCModuleOptions = {
Expand Down
95 changes: 95 additions & 0 deletions packages/nestjs-trpc/lib/drivers/__tests__/node.driver.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { NodeDriver } from '../node.driver';
import * as trpcNodeHttp from '@trpc/server/adapters/node-http';
import type { AnyRouter } from '@trpc/server';
import type { TRPCAdapterOptions } from '../../interfaces';

jest.mock('@trpc/server/adapters/node-http', () => ({
nodeHTTPRequestHandler: jest.fn().mockResolvedValue(undefined),
}));

describe('NodeDriver', () => {
const nodeHTTPRequestHandler =
trpcNodeHttp.nodeHTTPRequestHandler as jest.Mock;
const driver = new NodeDriver();
const appRouter = { _def: {} } as unknown as AnyRouter;
let app: any;

beforeEach(() => {
app = { use: jest.fn() };
});

afterEach(() => {
jest.clearAllMocks();
});

function mountedMiddleware(): (req: any, res: any) => void {
return app.use.mock.calls[0][1];
}

it('mounts on the configured base path', async () => {
await driver.start({ basePath: '/api/trpc' }, app, appRouter, null, null);

expect(app.use).toHaveBeenCalledWith('/api/trpc', expect.any(Function));
});

it('derives the procedure path from the prefix-stripped request url', async () => {
await driver.start({}, app, appRouter, null, null);

const req = { url: '/probe.hello?input=%7B%7D' };
const res = {};
mountedMiddleware()(req, res);

expect(nodeHTTPRequestHandler).toHaveBeenCalledWith(
expect.objectContaining({
router: appRouter,
path: 'probe.hello',
req,
res,
}),
);
});

it('passes adapter options through to nodeHTTPRequestHandler', async () => {
const responseMeta = jest.fn();

await driver.start({}, app, appRouter, null, null, {
maxBodySize: 1024,
responseMeta,
} as TRPCAdapterOptions);

mountedMiddleware()({ url: '/probe.hello' }, {});

expect(nodeHTTPRequestHandler).toHaveBeenCalledWith(
expect.objectContaining({
maxBodySize: 1024,
responseMeta,
router: appRouter,
}),
);
});

it('keeps the module-owned router and onError when adapter options carry them', async () => {
class TestErrorHandler {
onError = jest.fn();
}
const onErrorInstance = new TestErrorHandler();

await driver.start(
{ onError: TestErrorHandler },
app,
appRouter,
null,
onErrorInstance,
{
router: 'user-router',
onError: 'user-on-error',
} as unknown as TRPCAdapterOptions,
);

mountedMiddleware()({ url: '/probe.hello' }, {});

const handlerArgs = nodeHTTPRequestHandler.mock.calls[0][0];
expect(handlerArgs.router).toBe(appRouter);
expect(typeof handlerArgs.onError).toBe('function');
});
});
1 change: 1 addition & 0 deletions packages/nestjs-trpc/lib/drivers/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './fastify.driver';
export * from './express.driver';
export * from './node.driver';
56 changes: 56 additions & 0 deletions packages/nestjs-trpc/lib/drivers/node.driver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { Injectable } from '@nestjs/common';
import type { IncomingMessage, ServerResponse } from 'node:http';
import {
TRPCAdapterOptions,
TRPCContext,
TRPCErrorHandler,
TRPCModuleOptions,
} from '../interfaces';
import type { AnyRouter } from '@trpc/server';
import { nodeHTTPRequestHandler } from '@trpc/server/adapters/node-http';

export interface NodeApplication {
use(
path: string,
middleware: (req: IncomingMessage, res: ServerResponse) => void,
): unknown;
}

@Injectable()
export class NodeDriver<
TOptions extends Record<string, any> = TRPCModuleOptions,
> {
public async start(
options: TRPCModuleOptions,
app: NodeApplication,
appRouter: AnyRouter,
contextInstance: TRPCContext | null,
onErrorInstance: TRPCErrorHandler | null,
adapterOptions: TRPCAdapterOptions = {},
) {
app.use(options.basePath ?? '/trpc', (req, res) => {
const procedurePath = new URL(
req.url ?? '',
'http://127.0.0.1',
).pathname.slice(1);

void nodeHTTPRequestHandler<AnyRouter, IncomingMessage, ServerResponse>({
...adapterOptions,
router: appRouter,
path: procedurePath,
req,
res,
...(options.context != null && contextInstance != null
? {
createContext: (opts) => contextInstance.create(opts),
}
: {}),
...(options.onError != null && onErrorInstance != null
? {
onError: (opts) => onErrorInstance.onError(opts),
}
: {}),
});
});
}
}
2 changes: 1 addition & 1 deletion packages/nestjs-trpc/lib/factories/middleware.factory.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Inject, Injectable } from '@nestjs/common';
import { Class, Constructor } from 'type-fest';
import { TRPCMiddleware, TRPCModuleOptions } from '../interfaces';
import type { TRPCMiddleware, TRPCModuleOptions } from '../interfaces';
import { RouterFactory } from './router.factory';
import { ProcedureFactory } from './procedure.factory';
import { isEqual, uniqWith } from 'lodash';
Expand Down
4 changes: 3 additions & 1 deletion packages/nestjs-trpc/lib/interfaces/context.interface.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import type { CreateExpressContextOptions } from '@trpc/server/adapters/express';
import type { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';
import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';

export type ContextOptions =
| CreateExpressContextOptions
| CreateFastifyContextOptions;
| CreateFastifyContextOptions
| CreateHTTPContextOptions;

export interface TRPCContext {
create(
Expand Down
24 changes: 21 additions & 3 deletions packages/nestjs-trpc/lib/interfaces/module-options.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import type {
} from '@trpc/server';
import type { createExpressMiddleware } from '@trpc/server/adapters/express';
import type { FastifyTRPCPluginOptions } from '@trpc/server/adapters/fastify';
import type {
NodeHTTPHandlerOptions,
NodeHTTPRequest,
NodeHTTPResponse,
} from '@trpc/server/adapters/node-http';
import type { LoggerService } from '@nestjs/common';
import { TRPCContext } from './context.interface';
import type { TRPCErrorHandler } from './error-handler.interface';
Expand All @@ -24,12 +29,25 @@ import type {
*/
type ModuleOwnedTRPCOption = 'router' | 'createContext' | 'onError';

export type TRPCAdapterOptions =
| Omit<Parameters<typeof createExpressMiddleware>[0], ModuleOwnedTRPCOption>
type NodeAdapterHandlerOptions = NodeHTTPHandlerOptions<
AnyRouter,
NodeHTTPRequest,
NodeHTTPResponse
>;

export type TRPCAdapterOptions = (
| Omit<
Parameters<typeof createExpressMiddleware>[0],
ModuleOwnedTRPCOption | 'middleware'
>
| Omit<
FastifyTRPCPluginOptions<AnyRouter>['trpcOptions'],
ModuleOwnedTRPCOption
>;
>
| Omit<NodeAdapterHandlerOptions, ModuleOwnedTRPCOption | 'middleware'>
) & {
middleware?: NodeAdapterHandlerOptions['middleware'];
};

export type TRPCOptions = TRPCRuntimeConfigOptions<object, object> &
TRPCAdapterOptions &
Expand Down
Loading
Loading