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

@nclabs/nestjs-rpc-module

Package Overview
Dependencies
Maintainers
0
Versions
138
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nclabs/nestjs-rpc-module

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

  • 0.0.21
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
115
decreased by-39.15%
Maintainers
0
Weekly downloads
 
Created
Source

nestjs-nclabs-rpc-module

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



Instalação

npm i @nclabs/rpc-module


Configuração


# Environment variables

...

SERVICE_NAME= ## <indicar no environment do docker compose>


# ##################################################################### # 
#                                   NATS                                #
# ##################################################################### # 
NATS_HOST=<host>
NATS_PORT=<port>


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


# ##################################################################### # 
#                                   CACHE                               #
# ##################################################################### # 
CACHE_PREFIX=API-CACHE
CACHE_TTL=600
CACHE_HIT_LOG=true

...



Modulo

// app.module.ts

...
import { NclabsRpcModule } from '@nclabs/rpc-module';

@Module({
  imports: [    
    // ...
    NclabsRpcModule.register({ cache: true }),
    // ...
  ],
  // ...
})
export class AppModule {}



Recursos

RecursoTipoUsoObservação
NclabsActionDecoratorControllerConfigura requisições RPC e HTTP (opcional)
NclabsEventDecoratorControllerConfigura envio de eventos RPC
NclabsCtxDecoratorController ServiceAcessa informações do contexto do microserviço
NclabsContextInterface*Tipo de contexto do microserviço
NclabsRpcClientServiceProviderController ServiceMétodos para requisição de microserviços externos (RPC conf)
NclabsCacherServiceProviderController ServiceMétodos para o tratamento manual do cache
NclabsRxjsErrorHandlerLibObservable ApproachTrata exceções do microserviço (catchError)
NclabsExceptionLibPromise ApproachTrata exceções do microserviço
INclabsExceptionInterface*Tipo de exceção do microserviço


Controller - Method Configuration

// app.controller.ts

...

@Controller()
export class AppController {

  ...

  @NclabsAction({
    name: 'your-action-name',
    rest: {
      methods: ['GET', 'POST'],
      path: '/your-path',
    },
    cache: {
      keys: ['#headers.authorization', '#params.id', 'some-key'],
      ttl: 1200, // seconds
    },
  })
  youMethodName(@NclabsCtx() context: NclabsContext) {
    // Do something
    return;
  }

  ...

  • RPC: O método poderá ser requisitado pelo padrão service.name

    Onde:
    
      - service = SERVICE_NAME  (definido no environment do docker compose)
      - name    = your-action-name (configurado no decorator do método)
    

  • HTTP: A configuração rest do decorator irá disponibilizar 1 rotas de acesso HTTP para cada method:

    - GET /your-path
    - POST /your-path
    

  • CACHE: A configuração cache irá disponibilizar um cache para o retorno da requisição com as chaves especificadas no keys e com o TTL especificado no ttl.

    A chave do cache será criada concatenando:
    
      1. PATTERN       = <SERVICE_NAME.name> ou <SERVICE_NAME.method.path>
      2. authorization = informação do header `authorization`
      3. id            = atributo `id` do objeto `data` do contexto
      4. some-key      = texto estático
    
      key: PATTERN.Bearer A8DA9S8C9Asc098ca9s0ud0c0sgh.123.some-key
    

**** IMPORTANTE ****

Os decorator são processados antes da instanciação dos módulos e,
portanto, o ConfigService não está carregado.

Caso for utilizar variáveis de ambiente nas configurações, é 
necessário buscar o valor utilizando process.env.VARIABLE.


Contexto

// app.controller.ts
// app.service.ts

...

@Controller()
// ou
@Injectable()

  ...

  youMethod(@NclabsCtx() context: NclabsContext) {

    const { meta, headers, data } = context;

    // Meta:    Informações do microserviço (handler, subject e cadeia de chamadas)
    // Headers: Header do request
    // Data:    Body do request mesclado com os query parameters

    return;
  }

  ...



Client Service

// app.controller.ts
// app.service.ts

...

@Controller()
// ou
@Injectable()

  ...

  constructor(
    private readonly clientRpc: NclabsRpcClientService,
  ) {}

  ...

  youMethod(@NclabsCtx() context: NclabsContext): Obserable<Person> {

    const payload = { 
      name: 'John' 
    }; 

    return this.clientRpc.call('other-service.action', payload, context); 

  }

  ...



Exceptions

// app.controller.ts
// app.service.ts

...

@Controller()
// ou
@Injectable()

  ...


  /**
   * 
   * 
   */ 
  youMethod(token: string, includeG5 = false): Observable<IUser> {

    const url = `${baseUrl}platform/user/queries/getUser`;

    const headers = {
      Authorization: `Bearer ${token}`,
    };

    return this.httpService.get<IUser>(url, { headers }).pipe(
      // get data
      map((response: AxiosResponse<IUser>) => response.data),
      // append authentication
      map((data: IUser) => ({ ...data, authentication: `Bearer ${token}` })),
      // map response to IUser
      map(this._mapResponseToIUser),
      // generate password for G5
      map((user: IUser) => {
        if (includeG5) {
          const password = this._generateEncryptPassword(user.username);
          user.password = password;
          user.encryption = 2;
        }
        return user;
      }),
      catchError(NclabsRxjsErrorHandler),
    );
  }


  /**
   * 
   *  Generate password for G5
   * 
   */
  private _generateEncryptPassword(username: string): string {

    // create/get password

    if (!password || password === 'null') {
      const error = {
        code: 401,
        type: 'UNAUTHORIZED',
        message: 'Não foi possível gerar a senha encriptada do Senior G5',
        error: {
          jar: 'crypt.jar',
          encrypt: 'CBC',
          user: username,
          date: dt.toLocaleString('pt-BR', options).replace(',', ''),
        },
      };
      throw new NclabsException(error);
    }

    // do something

    return encryptedPassword;
  }

  ...



Keywords

FAQs

Package last updated on 18 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