Security News
The Risks of Misguided Research in Supply Chain Security
Snyk's use of malicious npm packages for research raises ethical concerns, highlighting risks in public deployment, data exfiltration, and unauthorized testing.
@nclabs/nestjs-rpc-module
Advanced tools
Utilitário NestJS para configuração de rotas e cache em microsserviços. Utilizado especificamente para projetos nclabs
Utilitário NestJS para configuração de rotas e cache em microsserviços. Utilizado especificamente para projetos nclabs
npm i @nclabs/rpc-module
# 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
...
// app.module.ts
...
import { NclabsRpcModule } from '@nclabs/rpc-module';
@Module({
imports: [
// ...
NclabsRpcModule.register({ cache: true }),
// ...
],
// ...
})
export class AppModule {}
Recurso | Tipo | Uso | Observação |
---|---|---|---|
NclabsAction | Decorator | Controller | Configura requisições RPC e HTTP (opcional) |
NclabsEvent | Decorator | Controller | Configura envio de eventos RPC |
NclabsCtx | Decorator | Controller Service | Acessa informações do contexto do microserviço |
INclabsContext | Interface | * | Tipo de contexto do microserviço |
NclabsRpcClientService | Provider | Controller Service | Métodos para requisição de microserviços externos (RPC conf) |
NclabsCacherService | Provider | Controller Service | Métodos para o tratamento manual do cache |
NclabsException | Lib | Promise Approach | Trata exceções do microserviço |
NclabsRxjsErrorHandler | Lib | Observable Approach | Trata exceções do microserviço (catchError) |
INclabsException | Interface | * | Tipo de exceção do microserviço |
// 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 GERADA:
PATTERN.Bearer A8D---.123.some-key
// 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;
}
...
// 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);
}
...
// 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;
}
...
FAQs
Utilitário NestJS para configuração de rotas e cache em microsserviços. Utilizado especificamente para projetos nclabs
The npm package @nclabs/nestjs-rpc-module receives a total of 111 weekly downloads. As such, @nclabs/nestjs-rpc-module popularity was classified as not popular.
We found that @nclabs/nestjs-rpc-module demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
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.
Security News
Snyk's use of malicious npm packages for research raises ethical concerns, highlighting risks in public deployment, data exfiltration, and unauthorized testing.
Research
Security News
Socket researchers found several malicious npm packages typosquatting Chalk and Chokidar, targeting Node.js developers with kill switches and data theft.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.