1.0.0-beta.4 • Published 2 months ago

@wolfcoded/nestjs-bufconnect v1.0.0-beta.4

Weekly downloads
-
License
MIT
Repository
github
Last release
2 months ago

GitHub license semantic-release: angular codecov npm version Known Vulnerabilities

Build Status

  • @beta beta
  • @main main

NestJs BufConnect

NestJs BufConnect is a custom transport strategy for NestJs microservices that integrates with the Buf's gRPC implementation. The library provides easy-to-use decorators for gRPC services and methods, allowing you to define and implement gRPC services seamlessly in your NestJs applications.

This project is in active development

Features

  • Decorators for defining gRPC services and methods
  • Integration with Buf's gRPC implementation
  • Custom transport strategy for NestJs microservices
  • Support for NestJs pipes, interceptors, guards, etc
  • HTTP, HTTPS, and HTTP2 support (secure and insecure)
    • Able to configure http server options without being constrained by abstraction
  • Support for gRPC streaming

Installation

pnpm add @wolfcoded/nestjs-bufconnect
yarn add @wolfcoded/nestjs-bufconnect
npm install @wolfcoded/nestjs-bufconnect --save

Usage

  1. Import ServerBufConnect from the @wolfcoded/nestjs-bufconnect package.
    import { ServerBufConnect } from '@wolfcoded/nestjs-bufconnect';
  2. Create a new instance of ServerBufConnect and pass it as the strategy in your microservice options.

    import { NestFactory } from '@nestjs/core';
    import { MicroserviceOptions } from '@nestjs/microservices';
    import {
      HttpOptions,
      ServerBufConnect,
      ServerProtocol,
    } from '@wolfcoded/nestjs-bufconnect';
    import { AppModule } from './app/app.module';
    
    const serverOptions: HttpOptions = {
      protocol: ServerProtocol.HTTP,
      port: 3000,
    };
    
    const app = await NestFactory.createMicroservice<MicroserviceOptions>(
      AppModule,
      {
        strategy: new ServerBufConnect(serverOptions),
      }
    );
    
    bootstrap();
  3. Use the BufService and BufMethod decorators to define your gRPC services and methods.

    import { Get } from '@nestjs/common';
    
    import { BufMethod, BufService } from '@wolfcoded/nestjs-bufconnect';
    import { AppService } from './app.service';
    import { ElizaService } from '../gen/eliza_connect';
    import { SayRequest } from '../gen/eliza_pb';
    
    @BufService(ElizaService)
    export class AppController {
      constructor(private readonly appService: AppService) {}
      // Standard controller method
      @Get()
      getData() {
        return this.appService.getData();
      }
    
      @BufMethod()
      async say(request: SayRequest) {
        console.log('calling say');
        return {
          sentence: `say() said: ${request.sentence}`,
        };
      }
    
      @BufStreamMethod()
      async *introduce(
        req: IntroduceRequest
      ): AsyncGenerator<{ sentence: string }> {
        yield { sentence: `Hi ${req.name}, I'm Eliza` };
        await delay(250);
        yield {
          sentence: `Before we begin, ${req.name}, let me tell you something about myself.`,
        };
        await delay(250);
        yield { sentence: `I'm a Rogerian psychotherapist.` };
        await delay(250);
        yield { sentence: `How are you feeling today?` };
      }
    }

NestJs Pipes, Guards, Interceptors, etc

NestJs BufConnect supports the use of NestJs pipes, guards, interceptors, etc.

import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Observable, from, lastValueFrom } from 'rxjs';
import { isAsyncGenerator } from '@wolfcoded/nestjs-bufconnect';

@Injectable()
export class ExampleInterceptor implements NestInterceptor {
  intercept(
    context: ExecutionContext,
    next: CallHandler
  ): Observable<any> | Promise<Observable<any>> {
    const req = context.switchToRpc().getData();
    console.log(`[Before] [${JSON.stringify(req)}]`);

    const streamOrValue = next.handle();

    return new Promise(async (resolve) => {
      console.log(`[Inner] [${JSON.stringify(req)}]`);
      const value = await lastValueFrom(streamOrValue);

      if (isAsyncGenerator(value)) {
        console.log(`[After] [${JSON.stringify(req)}]`);
        resolve(from(value));
      } else {
        console.log(`[After] [${JSON.stringify(req)}]`);
        resolve(streamOrValue);
      }
    });
  }
}

HTTP Support

NestJs BufConnect now provides support for different server protocols, including HTTP, HTTPS, and HTTP2 (secure and insecure). You can configure the desired protocol in the server options passed to the ServerBufConnect instance:

import {
  HttpOptions,
  ServerBufConnect,
  ServerProtocol,
} from '@wolfcoded/nestjs-bufconnect';

const serverOptions: HttpOptions = {
  protocol: ServerProtocol.HTTP, // or ServerProtocol.HTTPS, ServerProtocol.HTTP2, ServerProtocol.HTTP2_INSECURE
  port: 3000,
};

const strategy = new ServerBufConnect(serverOptions);

For HTTPS and HTTP2, you will need to provide additional options such as key, cert, and other relevant configuration options.

For example:

import {
  HttpsOptions,
  ServerBufConnect,
  ServerProtocol,
} from '@wolfcoded/nestjs-bufconnect';

const serverOptions: HttpsOptions = {
  protocol: ServerProtocol.HTTPS,
  port: 3000,
  serverOptions: {
    key: fs.readFileSync('path/to/your/private-key.pem'),
    cert: fs.readFileSync('path/to/your/certificate.pem'),
  },
};

const strategy = new ServerBufConnect(serverOptions);

This flexibility allows you to choose the right protocol for your application's requirements and security needs.

NOTE

  • Steaming support requires HTTP/2 and SSL (browsers typically don't support HTTP/2 unencrypted)

  • You can generate a self-signed certificate to get up and running quickly.

Install selfsigned

import * as selfsigned from 'selfsigned';
const attributes = [{ name: 'commonName', value: 'NestJsBufConnect' }];
const pems = selfsigned.generate(attributes, { days: 1 });

Todo

  • Add support for client-side gRPC services

MIT License

Copyright 2023 Patrick Wolf patrick.wolf@wisewolf.ai

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.