npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@wolfcoded/nestjs-bufconnect

v1.0.0-beta.4

Published

NestJs BufConnect is a custom transport strategy for NestJs microservices that integrates with the Buf's gRPC implementation.

Downloads

29

Readme

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 [email protected]

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.