Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@nclabs/rpc-config

Package Overview
Dependencies
Maintainers
0
Versions
75
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nclabs/rpc-config

Utilitário NestJS para configuração de rotas e cache em microserviços. Utilido especificamente para projetos nclabs

  • 1.1.7
  • unpublished
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
0
Maintainers
0
Weekly downloads
 
Created
Source

RPC Config

Utilitário para configuração de rotas e cache em microserviços. Utilido especificamente para projetos nclabs



Instalação

npm i @nclabs/rpc-config


Uso


Configuração


# Environment variables

...

# Quando compartilhar o mesmo .env, indicar o nome do serviço no 
# docker compose para idenficar o serviço correto
SERVICE_NAME=<service_name>  


# ##################################################################### # 
#                                 REDIS                                 #
# ##################################################################### # 
REDIS_HOST=<host>
REDIS_PORT=<port>
REDIS_PASSWORD=<password>
REDIS_DB=0

REDIS_CACHE_DB=0

...



Modulo
// app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { RpcConfigModule } from '@nclabs/rpc-config';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { CacherInterceptor } from '@nclabs/rpc-config';

@Module({
  imports: [    
    ...
    RpcConfigModule.forRoot({
      // Opcional - Pode ser omitido quando não for utilizar o cache
      cache: {
        prefix: process.env.CACHE_PREFIX,
        ttl: parseInt(process.env.CACHE_TTL, 10),
        logCacheHit: process.env.CACHE_HIT_LOG === 'true',
      },
    }),
    ...
  ],
  controllers: [AppController],
  providers: [
    AppService,
    // Opcional - Pode ser omitido quando não for utilizar o cache
    {
      provide: APP_INTERCEPTOR,
      useClass: CacherInterceptor,
    },
  ],
})
export class AppModule {}



Controller
// app.controller.ts

import { Action, Event, Rest } from '@nclabs/rpc-config';


@Controller()
export class AppController {
  ...

  /**
   * 
   *    REST 
   * 
   *    Permite que o metodo seja requisitado pela api-gateway.
   * 
   *    Na configuração abaixo as rotas GET e POST são permitidas na url: 
   * 
   *        <base_url>/user-credential/:id
   * 
   *        * base_url: http://<host>:<api_port>/<api_prefix>
   * 
   */  
  @Rest({
    rest: {
      methods: ['GET', 'POST'],
      path: '/user-credential/:id',
    },
    cache: {
      keys: ['#headers.authorization', "#params.username"],
      ttl: 1200, // 20 minutes
    },
  })
  userCredential(@Payload() params: { username: string }): Observable<UserCredential> {
    return this.appService.getUserCredential();
  }


  ...

  /**
   * 
   *    RPC ACTION
   * 
   *    Permite que o metodo seja requisitado através de um RPC client.
   * 
   *    * Mais informações em: 
   *      https://docs.nestjs.com/microservices/basics#sending-messages
   *        
   */  
  @Action({
    name: 'get-user-credential',
    cache: {
      keys: ['#params.apiKey'],
    },
  })
  getTokenFromKey(@Payload() params: { apiKey: string }): Obserable<UserCredential> {
    
    console.log('params', params);

    return this.appService.getUserCredential();
  }

  ...

  /**
   * 
   *    RPC EVENT
   * 
   * 
   *    Permite que o envio de um evento para o método através de um RPC client.
   * 
   *    * Mais informações em: 
   *      https://docs.nestjs.com/microservices/basics#publishing-events
   */  
  @Event({
    name: 'user-changed',
  })
  eventTeste(@Payload() params: UserPayload /* @Ctx() context: NatsContext */): void {
    
    // do something
    
    return;
  }

  ...
}

Keywords

FAQs

Package last updated on 12 Jul 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc