All Projects → flamewow → nestjs-asyncapi

flamewow / nestjs-asyncapi

Licence: MIT license
NestJS AsyncAPI module - generate the documentation of your event-based services using decorators

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language
shell
77523 projects

Projects that are alternatives of or similar to nestjs-asyncapi

nest-boilerplate
Nest.js boilerplate with CircleCI, Commitizen, Commitlint, Docker-Compose, ESLint, GitHub Actions, Husky, Lint-staged, OpenAPI, Prettier, PostGreSQL, Travis CI, TypeORM
Stars: ✭ 16 (-81.82%)
Mutual labels:  openapi, nest, nestjs
home
This is the home page for the API specification toolbox.
Stars: ✭ 16 (-81.82%)
Mutual labels:  openapi, asyncapi
boats
Beautiful Open Api Template System
Stars: ✭ 28 (-68.18%)
Mutual labels:  openapi, asyncapi
MyAPI
A template to create awesome APIs easily ⚡️
Stars: ✭ 117 (+32.95%)
Mutual labels:  nest, nestjs
openapi-filter
Filter internal paths, operations, parameters, schemas etc from OpenAPI/Swagger/AsyncAPI definitions
Stars: ✭ 112 (+27.27%)
Mutual labels:  openapi, asyncapi
cookbook
VueJS + NodeJS Evergreen Cookbook
Stars: ✭ 440 (+400%)
Mutual labels:  openapi, nestjs
modelina
Library for generating data models based on inputs such as AsyncAPI, OpenAPI, or JSON Schema documents.
Stars: ✭ 55 (-37.5%)
Mutual labels:  openapi, asyncapi
Stator
Stator, your go-to template for the perfect stack. 😍🙏
Stars: ✭ 217 (+146.59%)
Mutual labels:  nest, nestjs
twitch-project
A weekly stream in which I build a web application with Neo4j and Typescript
Stars: ✭ 78 (-11.36%)
Mutual labels:  nest, nestjs
nest-queue
Queue manager for NestJS Framework for Redis (via bull package)
Stars: ✭ 69 (-21.59%)
Mutual labels:  nest, nestjs
nest-rest-typeorm-boilerplate
🍱 backend with nest (typescript), typeorm, and authentication
Stars: ✭ 142 (+61.36%)
Mutual labels:  openapi, nest
Jwt
JWT utilities module based on the jsonwebtoken package 🔓
Stars: ✭ 232 (+163.64%)
Mutual labels:  nest, nestjs
Notadd
A microservice development architecture based on nest.js. —— 基于 Nest.js 的微服务开发架构。
Stars: ✭ 2,556 (+2804.55%)
Mutual labels:  nest, nestjs
prisma-generator-nestjs-dto
Generates NestJS DTO classes from Prisma Schema
Stars: ✭ 124 (+40.91%)
Mutual labels:  openapi, nestjs
Nestjs Typegoose
Typegoose with NestJS
Stars: ✭ 215 (+144.32%)
Mutual labels:  nest, nestjs
nestjs-telegraf
🤖 Powerful Nest module for easy and fast creation Telegram bots
Stars: ✭ 300 (+240.91%)
Mutual labels:  nest, nestjs
Mongoose
Mongoose module for Nest framework (node.js) 🍸
Stars: ✭ 191 (+117.05%)
Mutual labels:  nest, nestjs
Passport
Passport module for Nest framework (node.js) 🔑
Stars: ✭ 211 (+139.77%)
Mutual labels:  nest, nestjs
nestjs-ratelimiter
Distributed consistent flexible NestJS rate limiter based on Redis
Stars: ✭ 49 (-44.32%)
Mutual labels:  nest, nestjs
nestjs-objection
Objection module for NestJS
Stars: ✭ 24 (-72.73%)
Mutual labels:  nest, nestjs

StandWithUkraine

#StandWithUkraine

Description

AsyncApi module for Nest.

Generate AsyncApi documentation (for event-based services, like websockets) in a similar to nestjs/swagger fashion.

Documentation example

Installation

full installation (with chromium)

$ npm i --save nestjs-asyncapi

nestjs-async api package doesn't require chromium (which is required by asyncapi lib), so u can skip chromium installation by setting PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true environment variable.

$ PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true npm i --save nestjs-asyncapi

Quick Start

Document is composed via decorators.

Define AsyncApi service class by AsyncApiService decorator

  @AsyncApiService()

Define publish/subscribe methods by AsyncApiPub/AsyncApiSub decorators

  class AnySwaggerExampleDto {
    @ApiProperty()
    readonly name: string;
  }

  @AsyncApiPub({
    channel: 'test',
    summary: 'Send test packet',
    description: 'method is used for test purposes',
    message: {
      name: 'test data',
      payload: {
        type: AnySwaggerExampleDto,
      },
    },
  })

  @AsyncApiSub({
    channel: 'signal',
    summary: 'Subscribe to signal packet',
    description: 'method is used for test purposes',
    message: {
      name: 'test data signal',
      payload: {
        type: AnySwaggerExampleDto,
      },
    },
  })

Usage example:

gateway file:

import {
  ConnectedSocket,
  MessageBody,
  OnGatewayInit,
  OnGatewayDisconnect,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { Namespace, Server } from 'socket.io';
import { Logger } from '@nestjs/common';
import { Socket } from 'socket.io-client';
import { AsyncApiPub, AsyncApiService, AsyncApiSub } from 'nestjs-asyncapi';

@AsyncApiService()
@WebSocketGateway({ transports: ['websocket'], namespace: 'cats-ws' })
export class CatsGateway implements OnGatewayInit, OnGatewayDisconnect {
  @WebSocketServer()
  server: Server;
  private logger: Logger = new Logger(CatsGateway.name);

  afterInit(nsp: Namespace) {
    this.logger.log(`WS server init: ${nsp?.name}`);
  }

  handleDisconnect(client: Socket) {
    this.logger.log(`IOClient disconnected: ${client.id}`);
  }

  @SubscribeMessage('test')
  @AsyncApiPub({
    channel: 'test',
    summary: 'Send test packet',
    description: 'method is used for test purposes',
    message: {
      name: 'test data',
      payload: {
        type: AnySwaggerExampleDto,
      },
    },
  })
  test(@ConnectedSocket() client: Socket, @MessageBody() data: string) {
    this.logger.log(`data from client ${client.id} : ${JSON.stringify(data)}`);
    this.server.emit('test', data);
  }

  @AsyncApiSub({
    channel: 'signal',
    summary: 'Subscribe to signal packet',
    description: 'method is used for test purposes',
    message: {
      name: 'test data signal',
      payload: {
        type: AnySwaggerExampleDto,
      },
    },
  })
  async emitSignal(boardUUID: string, data: Record<string, any>) {
    this.server.to('test').emit('signal', data);
  }
}

main file:

import 'source-map-support/register';

import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { AppModule } from './src/app.module';
import { AsyncApiDocumentBuilder, AsyncApiModule, AsyncServerObject } from 'nestjs-asyncapi';

const port = 4001;
const host = '0.0.0.0';
const docRelPath = '/async-api';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  const asyncApiServer: AsyncServerObject = {
    url: 'ws://localhost:4001',
    protocol: 'socket.io',
    protocolVersion: '4',
    description: 'Allows you to connect using the websocket protocol to our Socket.io server.',
    security: [{ 'user-password': [] }],
    variables: {
      port: {
        description: 'Secure connection (TLS) is available through port 443.',
        default: '443',
      },
    },
    bindings: {},
  };

  const asyncApiOptions = new AsyncApiDocumentBuilder()
    .setTitle('Cats SocketIO')
    .setDescription('Cats SocketIO description here')
    .setVersion('1.0')
    .setDefaultContentType('application/json')
    .addSecurity('user-password', { type: 'userPassword' })
    .addServer('cats-server', asyncApiServer)
    .build();

  const asyncapiDocument = await AsyncApiModule.createDocument(app, asyncApiOptions);
  await AsyncApiModule.setup(docRelPath, app, asyncapiDocument);

  return app.listen(port, host);
}

const baseUrl = `http://${host}:${port}`;
const startMessage = `Server started at ${baseUrl}; AsyncApi at ${baseUrl + docRelPath};`;

bootstrap().then(() => console.log(startMessage));
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].