how to create NestJs grpc client - node.js

am trying to create a NestJs gRPC client on docker env, but i always get this error when compiling
[Nest] 1076 - 2020-05-19 23:59:34 [ClientProxy] The invalid gRPC package (package not found)
Error: The invalid gRPC package (package not found)
at ClientGrpcProxy.createClients (/app/node_modules/#nestjs/microservices/client/client-grpc.js:188:45)
at new ClientGrpcProxy (/app/node_modules/#nestjs/microservices/client/client-grpc.js:26:33)
at Function.create (/app/node_modules/#nestjs/microservices/client/client-proxy-factory.js:22:24)
at clients.map.item (/app/node_modules/#nestjs/microservices/module/clients.module.js:11:51)
at Array.map (<anonymous>)
at Function.register (/app/node_modules/#nestjs/microservices/module/clients.module.js:9:41)
at Object.<anonymous> (/app/dist/src/modules/orders/orders.module.js:31:43)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
/app/node_modules/#nestjs/microservices/client/client-grpc.js:190
throw invalidPackageError;
^
Error: The invalid gRPC package (package not found)
at ClientGrpcProxy.createClients (/app/node_modules/#nestjs/microservices/client/client-grpc.js:188:45)
at new ClientGrpcProxy (/app/node_modules/#nestjs/microservices/client/client-grpc.js:26:33)
at Function.create (/app/node_modules/#nestjs/microservices/client/client-proxy-factory.js:22:24)
at clients.map.item (/app/node_modules/#nestjs/microservices/module/clients.module.js:11:51)
at Array.map (<anonymous>)
at Function.register (/app/node_modules/#nestjs/microservices/module/clients.module.js:9:41)
at Object.<anonymous> (/app/dist/src/modules/orders/orders.module.js:31:43)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
i have already tried reinstalling the packages (gRPC, #grpc/proto-loader and #nestjs/microservices),
I get this problem when trying with both methods provided in docs
First Method with #Client decorator
#Client({
transport: Transport.GRPC,
options: {
package: 'app',
protoPath: join(__dirname, '../../../../../../src/modules/orders/proto/app.proto'),
},
})
private client : ClientGrpc
private grpcService: IGrpcService;
onModuleInit(){
this.grpcService= this.client.getService<IGrpcService>('AppController')
}
Second Method using ClientModule in appmodule.ts
ClientsModule.register([{
name:'TEST',
transport: Transport.GRPC,
options: {
package: 'app',
protoPath: join(__dirname, '../../../../src/modules/orders/proto/app.proto'),
},
}])
Proto file
syntax = "proto3";
package role;
service RoleService {
rpc CheckPermission (StringMessage) returns (BooleanPayload) {}
rpc AddPolicy (StringMessage) returns (BooleanPayload) {}
}
message StringMessage {
repeated string params = 1;
}
message Role {
string id = 1;
string codeName = 2;
string label = 3;
string createdAt = 4;
string updatedAt = 5;
}
message BooleanPayload {
bool success = 1;
}

I have fixed it, the problem was with my proto file Package and service, i've changed it to the name of the controller in using it in.

Follow question at here. Found a sample
Nest gGPC server: https://github.com/chj-damon/nestjs-grpc-server
Nest gGPC client: https://github.com/chj-damon/nestjs-grpc-client
Also, see more at a document gRPC client
Proto file:
syntax = "proto3";
package hero;
service HeroService {
rpc FindOne (HeroById) returns (Hero) {}
}
message HeroById {
int32 id = 1;
}
message Hero {
int32 id = 1;
string name = 2;
}
Controller:
import { Controller, OnModuleInit, Get, Param } from '#nestjs/common';
import {
GrpcMethod,
ClientGrpc,
Client,
Transport,
} from '#nestjs/microservices';
import { HeroById } from './interfaces/hero-by-id.interface';
import { Hero } from './interfaces/hero.interface';
import { Observable } from 'rxjs';
import { join } from 'path';
import { grpcClientOptions } from '../grpc-hero.options';
interface HeroService {
findOne(data: { id: number }): Observable<any>;
}
#Controller('hero')
export class HeroController implements OnModuleInit {
#Client(grpcClientOptions) private readonly client: ClientGrpc;
private heroService: HeroService;
onModuleInit() {
this.heroService = this.client.getService<HeroService>('HeroService');
}
#Get(':id')
call(#Param() params): Observable<any> {
return this.heroService.findOne({ id: +params.id });
}
}

Related

How to build server streaming via grpc and nest.js?

Need to create some "channel" to which the client can subscribe and periodically receive messages.
Within the current technology stack, I'm trying to organize something like this:
proto file:
syntax = "proto3";
package testtime;
service TimeService {
rpc GetTimeStream(Empty) returns (stream TimeStreamResponse);
}
message Empty {
}
message TimeStreamResponse {
string result = 1;
}
controller:
import { Controller } from '#nestjs/common';
import { GrpcMethod } from '#nestjs/microservices';
import moment from 'moment';
import { Observable, Subject } from 'rxjs';
const timeSubject = new Subject<{ result: string }>();
setInterval(() => {
const result = moment().format('hh:mm');
timeSubject.next({ result });
}, 5000);
#Controller()
export class TestTimeController {
#GrpcMethod('testtime.TimeService', 'GetTimeStream')
public getTimeStream(): Observable<{ result: string }> {
return timeSubject.asObservable();
}
}
when I try to call the method, I get an error:
/project/node_modules/#nestjs/microservices/server/server-grpc.js:141
this.transformToObservable(await handler).subscribe(data => callback(null, data), (err) => callback(err));
^
TypeError: callback is not a function
at SafeSubscriber._next (/project/node_modules/#nestjs/microservices/server/server-grpc.js:141:73)
at SafeSubscriber.__tryOrUnsub (/project/node_modules/rxjs/src/internal/Subscriber.ts:265:10)
at SafeSubscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:207:14)
at Subscriber._next (/project/node_modules/rxjs/src/internal/Subscriber.ts:139:22)
at Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
at CatchSubscriber.Subscriber._next (/project/node_modules/rxjs/src/internal/Subscriber.ts:139:22)
at CatchSubscriber.Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
at TapSubscriber._next (/project/node_modules/rxjs/src/internal/operators/tap.ts:125:22)
at TapSubscriber.Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
at MergeMapSubscriber.notifyNext (/project/node_modules/rxjs/src/internal/operators/mergeMap.ts:162:22)
at SimpleInnerSubscriber._next (/project/node_modules/rxjs/src/internal/innerSubscribe.ts:30:17)
at SimpleInnerSubscriber.Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
at MergeMapSubscriber.notifyNext (/project/node_modules/rxjs/src/internal/operators/mergeMap.ts:162:22)
at SimpleInnerSubscriber._next (/project/node_modules/rxjs/src/internal/innerSubscribe.ts:30:17)
at SimpleInnerSubscriber.Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
at SwitchMapSubscriber.notifyNext (/project/node_modules/rxjs/src/internal/operators/switchMap.ts:166:24)
What am I doing wrong?

Getting error when compiling and deploying ethereum smart contract with Node.js

I am trying to compile and deploy a smart contract to Rinkeby with a Node.js script. It is a course content I am following at Pluralsight. There it works, but it doesn't work for me. What is the error about?
NOTE: I have a solc compiler 0.7.0. When I change the pragma solidity to 0.7.0 and do all the appropriate changes the error doesn't change.
node deploy.js
Compiling the contract
assert.js:350
throw err;
^
AssertionError [ERR_ASSERTION]: Invalid callback object specified.
at runWithCallbacks (C:\COMP_DEV\blockchain\module_5\node_modules\solc\wrapper.js:97:7)
at compileStandard (C:\COMP_DEV\blockchain\module_5\node_modules\solc\wrapper.js:207:14)
at Object.compileStandardWrapper [as compile] (C:\COMP_DEV\blockchain\module_5\node_modules\solc\wrapper.js:214:14)
at compileContract (C:\COMP_DEV\blockchain\module_5\deploy.js:24:33)
at Object.<anonymous> (C:\COMP_DEV\blockchain\module_5\deploy.js:5:16)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
at Function.Module._load (internal/modules/cjs/loader.js:529:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
at startup (internal/bootstrap/node.js:285:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)
The contract is this one:
pragma solidity ^0.4.0;
contract Voter {
struct OptionPos {
uint pos;
bool exists;
}
uint[] public votes;
mapping (address => bool) hasVoted;
mapping (string => OptionPos) posOfOption;
string[] public options;
bool votingStarted;
function addOption(string option) public {
require(!votingStarted);
options.push(option);
}
function startVoting() public {
require(!votingStarted);
votes.length = options.length;
for (uint i = 0; i < options.length; i++) {
OptionPos memory option = OptionPos(i, true);
posOfOption[options[i]] = option;
}
votingStarted = true;
}
function vote(uint option) public {
require(0 <= option && option < options.length);
require(!hasVoted[msg.sender]);
hasVoted[msg.sender] = true;
votes[option] = votes[option] + 1;
}
function vote(string option) public {
require(!hasVoted[msg.sender]);
OptionPos memory optionPos = posOfOption[option];
require(optionPos.exists);
hasVoted[msg.sender] = true;
votes[optionPos.pos] = votes[optionPos.pos]++;
}
function getVotes() public view returns (uint[]) {
return votes;
}
}
and the deploy js script is this one:
let fs = require('fs');
let solc = require('solc')
let Web3 = require('web3');
let contract = compileContract();
let web3 = createWeb3();
let sender = "0xc3884e4e8e8ee58a7262a6c4910794e55513616a";
deployContract(web3, contract, sender)
.then(function () {
console.log('Deployment finished')
})
.catch(function (error) {
console.log(`Failed to deploy contract: ${error}`)
})
function compileContract() {
let compilerInput = {
'Voter': fs.readFileSync('Voter.sol', 'utf8')
};
console.log('Compiling the contract')
// Compile and optimize the contract
let compiledContract = solc.compile({sources: compilerInput}, 1);
// Get compiled contract
let contract = compiledContract.contracts['Voter:Voter']
// Save contract's ABI
let abi = contract.interface;
fs.writeFileSync('abi.json', abi);
return contract;
}
function createWeb3() {
let web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
return web3;
}
async function deployContract(web3, contract, sender) {
let Voter = new web3.eth.Contract(JSON.parse(contract.interface));
let bytecode = '0x' + contract.bytecode;
let gasEstimate = await web3.eth.estimateGas({data: bytecode});
console.log('Deploying the contract');
const contractInstance = await Voter.deploy({
data: bytecode
})
.send({
from: sender,
gas: gasEstimate
})
.on('transactionHash', function(transactionHash) {
console.log(`Transaction hash: ${transactionHash}`);
})
.on('confirmation', function(confirmationNumber, receipt) {
console.log(`Confirmation number: ${confirmationNumber}`);
})
console.log(`Contract address: ${contractInstance.options.address}`);
}
I got it fixed by matching the compiler version to the code version...

Problem tracking custom error with Application Insights: TypeError: Cannot read property 'stack' of undefined

I have written a custom error class and would like to track the error using Azure Application Insights. I am using Node.js. When I try tracking the custom error I get the following error:
TypeError: Cannot read property 'stack' of undefined
at Function.EnvelopeFactory.createExceptionData (/Users/liam/Desktop/CustomError/node_modules/applicationinsights/out/Library/EnvelopeFactory.js:145:40)
at Function.EnvelopeFactory.createEnvelope (/Users/liam/Desktop/CustomError/node_modules/applicationinsights/out/Library/EnvelopeFactory.js:32:40)
at NodeClient.TelemetryClient.track (/Users/liam/Desktop/CustomError/node_modules/applicationinsights/out/Library/TelemetryClient.js:116:44)
at NodeClient.TelemetryClient.trackException (/Users/liam/Desktop/CustomError/node_modules/applicationinsights/out/Library/TelemetryClient.js:69:14)
at Object.<anonymous> (/Users/liam/Desktop/CustomError/app.js:10:8)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
Here is the code:
class CustomError extends Error {
constructor (message) {
super(message)
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.status = 404;
}
statusCode() {
return this.status
}
}
const appInsights = require('applicationinsights');
appInsights.setup('MY_KEY').start();
let client = appInsights.defaultClient;
const customError = require('./exceptions');
let newError = new customError('The custom error was thrown')
client.trackException(newError);
I have done some research into TelemetryClient objects based on other resources online but I don't think that is the right direction.
I am using this resource as a guide: https://learn.microsoft.com/en-us/azure/azure-monitor/app/api-custom-events-metrics#trackexception
I was able to solve this problem by passing in a key value pair to trackException where the key is exception and the value is the error:
client.trackException({exception: new customError('This is a custom error')});
Full code:
class CustomError extends Error {
constructor (message) {
super(message)
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.status = 404;
}
statusCode() {
return this.status
}
}
const appInsights = require('applicationinsights');
appInsights.setup('MY_KEY').start();
let client = appInsights.defaultClient;
client.trackException({exception: new CustomError('This is a custom error')});

OOP - ES6 - Node Js - Calling parent method from children function - SyntaxError: 'super' keyword unexpected here

When I try to ejecute this code on Node.Js fail. I have created completed code to everybody be able to see real results.
This is classes's structure :
FILE printlog.js
const echo = require( 'node-echo' );
class printlog
{
p (msg) { echo(msg) }
}
exports.printlog = printlog;
File B.js
var { printlog } = require('./printlog.js')
class B extends printlog
{
constructor() {
super()
}
a_works(pos,elem) {
super.p(pos + ' - ' + elem)
}
a_fail(a_passed) {
if ( Array.isArray(a_passed) )
a_passed.forEach( function(elem, pos, array)
{
super.p(pos + ' - ' + elem ) // fail
})
}
}
var c = new B()
var arr = [2000, 2001, 2003,2039, 2040]
c.a_works(10,3) // works
c.a_fail(arr) // fail
Node Js version :
node -v
v8.6.0
Node command
node B.js
This is the error :
/B.js:25
super.p(pos + ' - ' + elem )
^^^^^
SyntaxError: 'super' keyword unexpected here
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:588:28)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)
at Function.Module.runMain (module.js:665:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:607:3
Thanks.
I tested the code just change echo() -> to console.log()
And Its works
class printlog
{
p (msg) { console.log(msg) }
}
class B extends printlog
{
constructor() {
super()
}
a(pos,elem) {
super.p(pos + ' - ' + elem)
}
}
const bb = new B();
bb.a('pos', 'sss');
Without all of your code, it's hard to guess what's wrong with it. I am assuming in your class constructor, you declare something like this.p = ''. Please provide your code.
The problem wasn't related to inheritance or other OOP issues.
What was failing is the method to iterate array, so seems using forEach we can't get other class methods (super , this )
If we change bucle by :
for (var i = 0; i < a_passed.length; i+=1)
Code works correctly.
Full Code :
File B.js
var { printlog } = require('./printlog.js')
class B extends printlog
{
constructor() {
super()
}
a_works(pos,elem) {
super.p(pos + ' - ' + elem)
}
a_dont_fail(a_passed) {
if ( Array.isArray(a_passed) )
for (var i = 0; i < a_passed.length; i+=1)
{
super.p(i + ' - ' + a_passed[i] ) // works
})
}
}
var c = new B()
var arr = [2000, 2001, 2003,2039, 2040]
c.a_works(10,3) // works
c.a_dont_fail(arr) // works
Thanks for read me.

Why am I getting a 'TypeError: undefined is not a function' here?

I am running into a strange (to me) error when trying to run the code specified below. The code compiles fine, but when I run it, node returns this error:
<location>/C.js:11
_super.call(this, "C");
^
TypeError: undefined is not a function
at new C (<location>/C.js:11:16)
at Function.B.factory (<location>/B.js:15:17)
at Function.Test.test (<location>/Test.js:6:18)
at Object.<anonymous> (<location>/app.js:2:6)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
Compile command: tsc --module commonjs -t ES5 app.ts
Run with: node app.js
Obviously I am new to both Typescript and Javascript, but I just can't see why this would fail. I have looked around for a solution but although this seems to be a common issue, I have come up empty for my particular problem. Can anyone shed some light on as to why this is happening? Here are the files:
A.ts
class A {
constructor(private name: string) {}
}
export = A;
B.ts
import A = require('./A');
import C = require('./C');
class B extends A {
constructor(value: string) {
super(value);
}
public static factory() {
var a: A = new C();
return a;
}
}
export = B;
C.ts
import B = require('./B');
class C extends B {
constructor() {
super("C");
}
}
export = C;
Test.ts
import B = require('./B');
class Test {
public static test() {
return B.factory();
}
}
export = Test;
app.ts
///<reference path='./typings/node/node.d.ts' />
import Test = require('./Test');
Test.test();
In order to save some space here, I pastebinned the generated javascript code. It can be found here if you're interested: javascript dump
This is because you have a circular dependency. C depends on B and B depends on C. Therefore B is undefined according to spec. https://nodejs.org/api/modules.html#modules_cycles

Resources