Node js client for grpc server - node.js

I have GRPC server running using openssl - static way and I am trying to connect to server using nodejs client
I do not see any error but I do not see its connecting to server either.
Please share if you have any sample.
Please refer code below:
var rootCertPath = path.join('.','.', 'server-root.PEM');
var privateCertPath = path.join('.','.', 'server-private.PEM');
var domainCertPath = path.join('.','.', 'server-domain.PEM');
var rootCert = fs.readFileSync(rootCertPath);
var privateCert = fs.readFileSync(privateCertPath);
var domainCert = fs.readFileSync(domainCertPath);
var buf1 = new Buffer('rootCert');
var buf2 = new Buffer('privateCert');
var buf3 = new Buffer('domainCert');
var chat_proto = grpc.load("Chat.proto").com.company.grpc;
var client = new chat_proto.ChatService('https://servervip:443',grpc.credentials.createSsl(buf1,buf2,buf3));
Chat.proto
syntax = "proto3";
// Service definition.
service ChatService {
// Sends a chat
rpc chat(stream ChatMessage) returns (stream ChatMessageFromServer) {}
}
// The request message containing the user's name.
message ChatMessage {
string name = 1;
string message = 2;
}
// The response message containing the greetings
message ChatMessageFromServer {
string name = 1;
string message = 2;
}
//Code to make a request
var username = process.argv[2];
var stdin = process.openStdin();
function main() {
console.log("starting");
console.log(client); // prints { '$channel': Channel {} }
var chat=client.chat();
chat.on('data', function(msg) {
console.log(msg.name + ': ' + msg.message);
console.log("after message");
});
stdin.addListener('data',function(input) {
chat.write({ name: username, message: input.toString().trim()
});
});
}
main();

so good new is - below thing worked for me
var rootCertPath = path.join('.','.', 'roots.PEM');
var rootCert = fs.readFileSync(rootCertPath);
var chat_proto = grpc.load("Chat.proto").com.americanexpress.grpc.chat;
var client = new chat_proto.ChatService('servervip:443',grpc.credentials.createSsl(rootCert));
Looks like an issue with the cert - I used the default roots.PEM in grpc client and it worked for me. will look internally to have correct root of my servervip CA certificate chain.
Thanks all for your support

Related

calling .net core 3.1 gRpc service from nodejs client

Using .net core 3.1 on windows 10. Created sample GrpcGreeter server and GrpcGreeterClient applications. From GrpcGreeterClient app, I can successfully call Greeter service.
greet.proto
syntax = "proto3";
option csharp_namespace = "GrpcGreeterClient";
package greet;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
client code;
static async Task Main(string[] args)
{
using var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(
new HelloRequest { Name = "GreeterClient" });
Console.WriteLine("Greeting: " + reply.Message);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
So far so good. However, when I try to call this same gRpc service from nodejs receved an error.
client proto file used in nodejs;
syntax = "proto3";
package greet;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
nodejs code in typescript;
let PROTO_PATH = path.resolve(__dirname, "../../proto/Greet.proto");
let packageDefinition = protoLoader.loadSync(PROTO_PATH);
const grpcObj = grpc.loadPackageDefinition(
packageDefinition
) as unknown as ProtoGrpcType;
const enmPackage = grpcObj.greet;
let client = new enmPackage.Greeter(
"localhost:5001",
grpc.credentials.createInsecure()
);
client.SayHello(
{
name: "Joe",
},
(err, reply) => {
if (err) {
console.error(err);
} else {
console.log(reply);
}
}
);
When I call client.SayHello, I received Error: 14 UNAVAILABLE: Connection dropped
What am I missing? Should I add any option in proto file?

Getting transaction events for a Bitcoin cash wallet address using GRPC interface

I have a simple script for listening to Unconfirmed and Confirmed transaction on a Bitcoin cash wallet. I am connecting to a GRPC interface for getting these messages. The script works well and I get the unconfirmed transaction every time a transfer takes place. However, I do not receive any messages for confirmed transaction.
Here's the code I have:
var PROTO_PATH = __dirname + '/bchrpc.proto';
var fs = require('fs');
var bchaddr = require('bchaddrjs');
var axios = require('axios');
var grpc = require('#grpc/grpc-js');
var protoLoader = require('#grpc/proto-loader');
var packageDefinition = protoLoader.loadSync(
PROTO_PATH,
{keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
});
var pb = grpc.loadPackageDefinition(packageDefinition).pb;
var client = new pb.bchrpc('bchd.imaginary.cash:8335', grpc.credentials.createSsl());
var addr = '<WALLET_ADDRESS>';
console.log(addr);
// Build TransactionFilter & setup live transaction stream
var transactionFilter = pb.TransactionFilter
transactionFilter.all_transactions = false;
transactionFilter.addresses = [addr];
var subscribreTransactionsRequest = pb.SubscribeTransactionsRequest;
subscribreTransactionsRequest.include_mempool = true;
subscribreTransactionsRequest.subscribe = transactionFilter;
var stream = client.SubscribeTransactions(subscribreTransactionsRequest)
function dataHandler(message) {
console.log('New Transaction');
var tx = message
console.log(tx);
const { type } = tx;
// map hashes to strings
switch(type) {
case 'UNCONFIRMED':
console.log('Inputs:');
console.log(tx.unconfirmed_transaction.transaction.inputs);
console.log('----------------\nOutputs');
console.log(tx.unconfirmed_transaction.transaction.outputs);
console.log('---------------------------');
const h1 = tx.unconfirmed_transaction.transaction.hash;
fs.writeFileSync('unconfirmed.txt', `${h1.toString('hex')}\n`, { encoding: 'utf-8', flag: 'a+' });
break;
case 'CONFIRMED':
console.log('Inputs:');
console.log(tx.confirmed_transaction.transaction.inputs);
console.log('----------------\nOutputs');
console.log(tx.confirmed_transaction.transaction.outputs);
console.log('---------------------------');
const h2 = tx.confirmed_transaction.transaction.hash;
fs.writeFileSync('confirmed.txt', `${h2.toString('hex')}\n`, { encoding: 'utf-8', flag: 'a+' });
break;
}
// post
axios.post(URL, tx).then(res => {
console.log(res.status);
}).catch(e => console.error(e));
}
// other functions omitted for brevity
stream.on('data', dataHandler);
stream.on('status', statusHandler);
stream.on('end', endHandler);
stream.on('error', errorHandler);
The script listens for all events on this given address and on data event, invokes dataHandler function which prints the transaction information, writes the transaction hash to a file and finally, sends the transaction information to a remote address. On RST_STREAM error, the script reconnects to the server after 1 second delay. The script uses bchrpc.proto protocol buffer definition from this package here.
Is there anything missing in my code that results in this behavior or, is it because the connecting server is unreliable on message delivery? I also tried the following servers with the same results:
https://bchd.greyh.at:8335
https://bchd.fountainhead.cash:443
Any help on this highly appreciated. Thanks.
I was finally able to figure out the issue after looking at other example scripts. I was missing one option in the subscribreTransactionsRequest that cause the issue and here's the change that solved the issue:
subscribreTransactionsRequest.include_in_block = true;
From the protocol buffer definition:
// When include_in_block is true, transactions are included when they are confirmed. This notification is sent in addition to any requested mempool notifications.
bool include_in_block = 4;
Adding the answer here for future reference.

How to connect Javascript to a remote IBM MQ?

I'm making APIs with LoopBack( a Javascript Framework), pushing and getting messages with IBM MQ.
I followed this tut: Nodejs and MQ
I can do it with local Queue Manager, but I dont know how to connect to a remote Queue Manager.
So, can any one explain me how to do this ?
Tks all.
I can do it with that link, which from #JoshMc's comment.
This is my code, it works fine:
module.exports = function (server) {
var mq = require('ibmmq');
var MQC = mq.MQC; // Want to refer to this export directly for simplicity
// The queue manager and queue to be used. These can be overridden on command line.
var qMgr = "QM1";
var qName = "soa.log";
var mqmd = new mq.MQMD(); // Defaults are fine.
var pmo = new mq.MQPMO();
var cd = new mq.MQCD();
var cno = new mq.MQCNO();
cd.ConnectionName = "localhost(1414)";
cd.ChannelName = "CHAN1";
var csp = new mq.MQCSP();
cno.ClientConn = cd;
cno.Options = MQC.MQCNO_CLIENT_BINDING; // use MQCNO_CLIENT_BINDING to connect as client
function putMessage(hObj) {
var msg = Buffer.from(JSON.stringify(coff));
// Describe how the Put should behave
pmo.Options = MQC.MQPMO_NO_SYNCPOINT |
MQC.MQPMO_NEW_MSG_ID |
MQC.MQPMO_NEW_CORREL_ID;
mq.Put(hObj,mqmd,pmo,msg,function(err) {
if (err) {
console.log(formatErr(err));
} else {
console.log("MQPUT successful");
}
});
}
mq.Connx(qMgr, cno, function (err, hConn) {
if (err) {
console.log((err));
} else {
console.log("MQCONN to %s successful ", qMgr);
// Define what we want to open, and how we want to open it.
var od = new mq.MQOD();
od.ObjectName = qName;
od.ObjectType = MQC.MQOT_Q;
var openOptions = MQC.MQOO_OUTPUT;
mq.Open(hConn, od, openOptions, function (err, hObj) {
if (err) {
console.log(formatErr(err));
} else {
console.log("MQOPEN of %s successful", qName);
putMessage(hObj);
}
// cleanup(hConn, hObj);
});
}
});
};

How to read and get events from zoho calendar using CalDav in node.js

I want to communicate from backend with the calendar using caldav of zoho mail using nodejs. Could anyone suggest me how to implement it?
I am using plugin node-caldav-mod
I tried this piece of code which doesn't seem to be working.
var caldav = require("node-caldav-mod");
var moment = require('moment-timezone');
var express = require('express');
var app = express();
var xmljs = require("libxmljs");
var https = require("https");
var CalendarId = "2123123123";
var url = "https://calendar.zoho.com/caldav/{CalendarId}/events";
var username = "username"
var password = "password"
var timeFormat = "YYYYMMDDTHHmms";
var getTodayEvent = function (callback){
var startDate = moment().set({'hour': 0,'minute': 0,'second': 0}).format(timeFormat) + "Z";
var endDate = moment().set({'hour': 23,'minute': 59,'second': 59}).format(timeFormat) + "Z";
var output = {};
output.startDate = startDate;
output.endDate = endDate;
caldav.getEvents(url, username, password, startDate, endDate, function(response){
console.log(response);
callback(response);
});
}
var findPropertyNameByRegex = function(o, r) {
var key;
for (key in o) {
if (key.match(r)) {
return key;
}
}
return undefined;
};
function compare(a,b) {
var startDate_a = findPropertyNameByRegex(a, "DTSTART");
var startDate_b = findPropertyNameByRegex(b, "DTSTART");
if (a[startDate_a] < b[startDate_b])
return -1;
else if (a[startDate_a] > b[startDate_b])
return 1;
else
return 0;
}
app.get('/today',function(req, res){
getTodayEvent(function(events){
events.sort(compare);
res.send("Communication set up properly!")
})
});
This is the error which I am getting
Parsing.....
undefined
Error parsing response
TypeError: Cannot read property 'D:multistatus' of undefined
Could somebody tell me what's wrong with this code?
Could somebody tell me what's wrong with this code?
Yes. Your error seems to come from
this line
in the module you seem to use:
var data = result['D:multistatus']['D:response'];
Which is utter non-sense. D: is just a namespace prefix and can be anything the server chooses.
A CalDAV client needs to properly parse and process XML namespaces.
Solution: Use a proper module, or just write it on your own.

Send message using telegram bot with Node.js

I'm doing a service to warn me of possible errors that can occur on my server , my doubt is , after I send a message as I finalize the execution or the way it is presenting the image below normal? For to complete the task I have to take a ctrl + c
code:
var util = require('util');
var TelegramBot = require('node-telegram-bot-api');
var token = '237907874:AAG8hK1lPWi1WRlqQT2';
var bot = new TelegramBot(token, {polling: true});
var millisecondsToWait = 5000;
robot = {
"alert": function teste(message) {
var toId = '-103822200';
var resp = util.format('alerta: %s', message);
bot.sendMessage(toId, resp);
}
}
robot.alert(process.argv[2]);
in cmd i execute this code
node.exe bot.js 'text send'
this is image
Looks like some error occurs but not captured:
var robot = { // Don't forget about var :)
"alert": function teste(message) {
var toId = '-103822200';
var resp = util.format('alerta: %s', message);
bot.sendMessage(toId, resp)
.catch(function(error){ // Catch possible error
console.error(error);
});
}
}

Resources