@funduck/connectrpc-fastify-nestjs
v1.0.11
Published
Wrapper for official @connectrpc/connect and fastify integrated into Nestjs. Simplifies configuration, type safe binding to controller, simplifies use of middlewares.
Readme
Connectrpc Fastify Wrapper For Nestjs
Repo on github
Package on npm
Related base repo without Nestjs
Description
This package allows to add Connectrpc into Nestjs project using the Fastify server.
If you are comfortable with HTTP/1 only and want a compact, ready-to-use setup, this repository is for you.
It simplifies the binding of controllers and middlewares.
It uses my another package Connectrpc Fastify Wrapper.
Features
This library allows you to:
- Use only HTTP/1 transport
- Perform RPC with simple request and response messages
- Perform RPC with streaming responses
- Perform RPC with streaming requests
- Use middlewares
- Use interceptors
Bidirectional streaming RPC is currently out of scope because it requires HTTP/2, which is unstable on public networks. In practice, HTTP/1 provides more consistent performance.
How To Use
You can check out the test/demo directory for a complete example of server and client integration using NestJS and Fastify. Start reading from test/demo/app.module.ts.
Except the bootstrap instructions are pretty much the same as in Connectrpc Fastify Wrapper.
Controllers
Controller must implement the service interface (not all methods) and register itself using ConnectRPC.registerController:
@Injectable()
export class ElizaController implements Service<typeof ElizaService> {
@Inject(Logger)
private logger: Logger;
constructor() {
ConnectRPC.registerController(this, ElizaService);
}
async say(
request: SayRequest,
) {
return {
sentence: `You said: ${request.sentence}`,
};
}
// ... Other methods are optional
}Middlewares
Middleware must implement Middleware interface and register itself using ConnectRPC.registerMiddleware:
@Injectable()
export class TestMiddleware1 implements Middleware {
@Inject(Logger)
private logger: Logger;
constructor() {
ConnectRPC.registerMiddleware(this);
}
use(req: FastifyRequest['raw'], res: FastifyReply['raw'], next: () => void) {
next();
}
}
Interceptors
Interceptor must implement Interceptor interface and register itself using ConnectRPC.registerInterceptor:
@Injectable()
export class TestInterceptor1 implements Interceptor {
@Inject(Logger)
private logger: Logger;
constructor() {
ConnectRPC.registerInterceptor(this);
}
use(next: AnyFn): AnyFn {
return async (req) => {
this.logger.log(`TestInterceptor1 invoked`);
return await next(req);
};
}
}
Module Setup
Configure your NestJS module to use ConnectRPCModule.forRoot and register middlewares and interceptors as providers if necessary:
@Module({
imports: [
// Configure ConnectRPCModule
ConnectRPCModule.forRoot({
logger: new Logger('ConnectRPC', { timestamp: true }),
middlewares: [
middlewareConfig(TestMiddleware1),
middlewareConfig(TestMiddleware2, ElizaService),
middlewareConfig(TestMiddleware3, ElizaService, ['say']),
],
interceptors: [
interceptorConfig(TestInterceptor1),
interceptorConfig(TestInterceptor2, ElizaService),
interceptorConfig(TestInterceptor3, ElizaService, ['say']),
],
}),
],
providers: [
Logger,
// Controllers are provided here instead of `controllers` array
ElizaController,
// Middlewares specific for ConnectRPC are provided here
TestMiddleware1,
TestMiddleware2,
// Middlewares that are applied via `consumer.apply()` should NOT be provided here
// Do not instantiate TestMiddleware3 twice!
// Interceptors specific for ConnectRPC are provided here
TestInterceptor1,
TestInterceptor2,
TestInterceptor3,
],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(TestMiddleware3).forRoutes('*'); // TestMiddleware3 is instantiated here!
}
}Server Bootstrap
Just add the call to ConnectRPCModule after creating the app:
export async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
);
// After the app is created, register the ConnectRPCModule
await app.get(ConnectRPCModule).registerPlugin();
await app.listen(3000);
}Strict Mode
If strict mode is enabled the library will cause process to exit on errors such as missing middleware or interceptor instances.
By default, strict mode is disabled to allow more flexibility during development.
To enable it call ConnectRPC.setStrictMode(true) before registering any middlewares or interceptors.
To check it read ConnectRPC.isStrictMode property.
More examples
See test/demo and examples directories for more examples.
Feedback
Please use Discussions or email me.
