npm package: @funduck/connectrpc-fastify-nestjs
Description: Wrapper for official @connectrpc/connect and fastify integrated into Nestjs. Simplifies configuration, type safe binding to controller, simplifies use of middlewares.
Author: Oleg Milekhin
Latest version: 1.0.12

# Connectrpc Fastify Wrapper For Nestjs
<img src="./coverage/badge.svg" alt="Coverage Badge" />

Repo on [github](https://github.com/funduck/connectrpc-fastify-nestjs)  
Package on [npm](https://www.npmjs.com/package/@funduck/connectrpc-fastify-nestjs)  
Related [base repo without Nestjs](https://github.com/funduck/connectrpc-fastify)

## Description

This package allows to add [Connectrpc](https://github.com/connectrpc/connect-es) into [Nestjs](https://github.com/nestjs/nest) project using the [Fastify](https://github.com/fastify/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](https://github.com/funduck/connectrpc-fastify).

## 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](https://github.com/funduck/connectrpc-fastify#how-to-use).

### Controllers
Controller must implement the service interface (not all methods) and register itself using `ConnectRPC.registerController`:
```TS
@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`:
```TS
@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`:
```TS
@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:

```typescript
@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:

```typescript
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](https://github.com/funduck/connectrpc-fastify-nestjs/discussions) or email me.