Skip to content
Open
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
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
node_modules
dist
.vscode
.vscode

*.lock
*.log
15 changes: 11 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,24 +26,28 @@
"scripts": {
"build": "tsc",
"dev": "tsc -w",
"dev:watch": "nodemon --watch src --ext ts --exec \"ts-node\" src/example/index.ts",
"lint": "eslint --ext .ts src/"
},
"peerDependencies": {
"@nestjs/common": "^9.2.1",
"@nestjs/core": "^9.2.1",
"@nestjs/platform-express": "^9.2.1",
"@nestjs/platform-fastify": "^9.4.2",
"@trpc/server": "~10.10.0",
"reflect-metadata": "^0.1.12",
"rxjs": "^7.1.0"
"rxjs": "^7.1.0",
"fastify": "^4.17.0"
},
"dependencies": {
"@fastify/cookie": "^8.3.0"
},
"dependencies": {},
"devDependencies": {
"@nestjs/common": "^9.2.1",
"@nestjs/core": "^9.2.1",
"@nestjs/platform-express": "^9.2.1",
"@nestjs/platform-fastify": "^9.4.2",
"@trpc/server": "~10.10.0",
"reflect-metadata": "^0.1.12",
"rxjs": "^7.1.0",
"@types/node": "^16.0.0",
"@typescript-eslint/eslint-plugin": "^5.48.2",
"@typescript-eslint/parser": "^5.48.2",
Expand All @@ -52,6 +56,9 @@
"eslint-config-airbnb-typescript": "^17.0.0",
"eslint-plugin-import": "^2.25.2",
"nodemon": "^2.0.20",
"reflect-metadata": "^0.1.12",
"rxjs": "^7.1.0",
"ts-node": "^10.9.1",
"typescript": "^4.9.4"
},
"files": [
Expand Down
4 changes: 2 additions & 2 deletions src/example/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { Module } from '@nestjs/common';
import { TrpcModule } from '../lib/trpc.module';
import { AModule } from './domain-b/a.module';
import { appRouter } from './init-trpc';
import { appRouter, createContext } from './init-trpc';

@Module({
imports: [
AModule,
TrpcModule.forRoot({
path: '/trpc',
router: appRouter,
createContext: () => ({}),
createContext,
}),
],
})
Expand Down
11 changes: 9 additions & 2 deletions src/example/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
/* eslint-disable import/no-extraneous-dependencies */
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import fastifyCookie from '@fastify/cookie';
import { AppModule } from './app.module';

async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
app.register(fastifyCookie);

await app.listen(3000);
}

Expand Down
20 changes: 15 additions & 5 deletions src/example/init-trpc.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
/* eslint-disable import/no-extraneous-dependencies */
import { initTRPC } from '@trpc/server';
import { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';
import { FastifyReply, FastifyRequest } from 'fastify';
import { InferContextType } from '../lib/infer-context-type.type';
import { AService } from './domain-b/a.service';

// You can use any variable name you like.
// We use t to keep things simple.
type CtxType = InferContextType<typeof createContext>;
const createContext = () => ({
someValueOnContext: 'randomValue',
});

export const createContext = ({ req }: CreateFastifyContextOptions) => {
const { hostname } = req;

return {
hostname,
someValueOnContext: 'randomValue',
};
};

type CtxType = InferContextType<typeof createContext, FastifyRequest, FastifyReply>;

const trpc = initTRPC.context<CtxType>().create({

});
Expand All @@ -18,7 +29,6 @@ const publicProcedure = trpc.procedure;
export const appRouter = router({
something: publicProcedure.query(async ({ ctx }) => {
const service = await ctx.resolveNestDependency(AService);
console.log({ service });
return service.smth();
}),
});
43 changes: 37 additions & 6 deletions src/lib/attach-trpc-to-express-app.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
import { NestExpressApplication } from '@nestjs/platform-express';
import type { NestExpressApplication } from '@nestjs/platform-express';
import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify';
import type { FastifyInstance } from 'fastify';
import { TrpcModuleOptions } from './trpc-module-options.type';
import {
buildTrpcNestMiddleware,
BuildTrpcNestMiddlewareOptions,
extendTrpcContext,
} from './build-trpc-nest-middleware';

import { buildTrpcNestMiddleware, BuildTrpcNestMiddlewareOptions } from './build-trpc-nest-middleware';
type ExpressApp = {
expressApp?: NestExpressApplication,
fastifyApp?: never,
} & TrpcModuleOptions & BuildTrpcNestMiddlewareOptions;

interface Options extends TrpcModuleOptions, BuildTrpcNestMiddlewareOptions {
expressApp: NestExpressApplication,
}
type FastifyApp = {
expressApp?: never,
fastifyApp?: FastifyInstance,
} & TrpcModuleOptions & BuildTrpcNestMiddlewareOptions;

type Options = ExpressApp | FastifyApp;

/**
* Attaches a TRPC router to your nestExpressApp
Expand All @@ -20,5 +33,23 @@ export function attachTrpcToExpressApp({
createContext,
});

expressApp.use(path, trpcNestMiddleware);
expressApp?.use(path, trpcNestMiddleware);
}

/**
* Attaches a TRPC router to your fastifyApp
* @param options: Options
*/
export function attachTrpcToFastifyApp({
router, moduleRef, createContext, path, fastifyApp,
}: Options): void {
fastifyApp?.removeContentTypeParser(['application/json']);

fastifyApp?.register(fastifyTRPCPlugin, {
prefix: path,
trpcOptions: {
router,
createContext: extendTrpcContext(createContext, moduleRef),
},
});
}
16 changes: 16 additions & 0 deletions src/lib/build-trpc-nest-middleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createHTTPHandler } from '@trpc/server/adapters/standalone';
import { ModuleRef } from '@nestjs/core';
import { AnyRouter } from '@trpc/server';
import { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';
import { buildNestResolver } from './build-nest-resolver';

export interface BuildTrpcNestMiddlewareOptions {
Expand Down Expand Up @@ -36,10 +37,25 @@ export function buildTrpcNestMiddleware({ moduleRef, router, createContext }: Bu
const userProvidedContext = createContext();

return {
req,
res,
...userProvidedContext,
resolveNestDependency,
};
},
})(req, res);
};
}

export function extendTrpcContext(origContext: (args: CreateFastifyContextOptions) => any, moduleRef: ModuleRef) {
return function createContext({ req, res }: CreateFastifyContextOptions) {
const { resolveNestDependency } = buildNestResolver(req, moduleRef);

return {
...origContext({ req, res }),
req,
res,
resolveNestDependency,
};
};
}
9 changes: 5 additions & 4 deletions src/lib/infer-context-type.type.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { inferAsyncReturnType } from '@trpc/server';
import { IncomingMessage, ServerResponse } from 'http';
import { NestResolver } from './nest-resolver.type';

export type InferContextType<TContext> =
TContext extends () => any
? inferAsyncReturnType<TContext> & NestResolver
: NestResolver;
export type InferContextType<TContext, TReq = IncomingMessage, TRes = ServerResponse> =
TContext extends (args?:any) => any
? inferAsyncReturnType<TContext> & NestResolver<TReq, TRes>
: NestResolver<TReq, TRes>;
10 changes: 9 additions & 1 deletion src/lib/nest-resolver.type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ interface Type<T = any> extends Function {
new(...args: any[]): T;
}

export interface NestResolver {
export interface NestResolver<TReq = any, TRes = any> {
/**
* Resolves any NestJS dependency from your project. a proxy to `moduleRef.get()`
*
Expand All @@ -12,4 +12,12 @@ export interface NestResolver {
* Returns a promise which resolves to the dependency.
*/
resolveNestDependency: <TInput = any, TResult = TInput>(typeOrToken: Type<TInput> | Function | string | symbol) => Promise<TResult>;

/**
*
* Include request and response objects
*
*/
req: TReq,
res: TRes,
}
2 changes: 1 addition & 1 deletion src/lib/trpc-module-options.type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ import { AnyRouter } from '@trpc/server';
export interface TrpcModuleOptions<TRouter = AnyRouter> {
path: '/trpc' | string;
router: TRouter;
createContext: () => any;
createContext: (args?: any) => any;
}
6 changes: 3 additions & 3 deletions src/lib/trpc.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
DynamicModule, Inject, Module, OnModuleInit,
} from '@nestjs/common';
import { HttpAdapterHost, ModuleRef } from '@nestjs/core';
import { attachTrpcToExpressApp } from './attach-trpc-to-express-app';
import { attachTrpcToFastifyApp } from './attach-trpc-to-express-app';
import { TRPC_CREATE_CONTEXT_TOKEN, TRPC_PATH_TOKEN, TRPC_ROUTER_TOKEN } from './tokens';
import { TrpcModuleOptions } from './trpc-module-options.type';

Expand Down Expand Up @@ -40,9 +40,9 @@ export class TrpcModule implements OnModuleInit {
}

onModuleInit() {
attachTrpcToExpressApp({
attachTrpcToFastifyApp({
moduleRef: this.moduleRef,
expressApp: this.httpAdapterHost.httpAdapter.getInstance(),
fastifyApp: this.httpAdapterHost.httpAdapter.getInstance(),
path: this.path,
createContext: this.createContext,
router: this.router,
Expand Down
Loading