I have a simple gRPC server and client. The server and client are working fine (I assume since I am getting a response and no error). However the response is empty which I have no idea why.
Here is the proto message.proto
syntax = "proto3";
message Msg {
int32 timeStamp = 1;
string text = 2;
string sender = 3;
}
message Empty {}
service MsgService{
rpc AllMessages (Empty) returns (MsgList) {}
}
message MsgList {
repeated Msg msgs = 1;
}
and server.js
const grpc = require('@grpc/grpc-js');
const PROTO_PATH = "./message.proto";
const protoLoader = require('@grpc/proto-loader');
const options = {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
}
const packageDefinition = protoLoader.loadSync(PROTO_PATH, options);
const msgProto = grpc.loadPackageDefinition(packageDefinition);
const server = new grpc.Server();
let savedMessages = [
{ timeStamp: 1, text: "lorem", sender: "alex" },
{ timeStamp: 2, text: "ipsum", sender: "bob" },
{ timeStamp: 3, text: "dolor", sender: "alex" },
{ timeStamp: 4, text: "net", sender: "bob" }
];
server.addService(msgProto.MsgService.service, {
AllMessages: (_, callback) => {
callback(null, savedMessages);
}
})
server.bindAsync("127.0.0.1:50051", grpc.ServerCredentials.createInsecure(), (err, port) => {
if (err) {
console.log(err);
}
console.log(port);
server.start();
console.log("Server running at 127.0.0.1:50051");
})
and client.js
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const PROTO_PATH = "./message.proto";
const options = {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
};
var packageDefinition = protoLoader.loadSync(PROTO_PATH, options);
const MsgService = grpc.loadPackageDefinition(packageDefinition).MsgService;
const client = new MsgService(
"localhost:50051",
grpc.credentials.createInsecure()
);
client.AllMessages({}, (err, msg) => {
// console.log(err);
if (err) throw err;
console.log(msg);
// console.log(msg);
})
and the repsonse I am getting
{ msgs: [] }
If it helps , I was following this blog post https://daily.dev/blog/build-a-grpc-service-in-nodejs
Thanks in advance.
CodePudding user response:
Your MsgList
message definition is a message with a single field called msgs
that has the type repeated Msg
. The object that you send should have that form. So, it should be an object with a single field called msgs
that has an array of objects that match the format of the Msg
message definition. Your savedMessages
variable is not that, it's just an array, which is why sending it doesn't get the result you want.