I'm writing an RPC function that returns an object from MongoDB where the user can define the returned parameters in the call. The problem is that I can't seem to find how to define a 'dynamic' object in the proto. All the examples I find are based on an object that is static and all the parameters are set in the .proto file. The RPC function looks like this:
function fetch(call, callback) {
ObjectSvc.getById(call.request.id, call.request.parameter, (err, object) => {
if (err) {
log.error(err);
callback(err);
} else {
callback(null, object);
}
});
};
My .proto definition looks like this:
package object;
service Object{
rpc fetch (queryReq) returns (objectRes) {}
}
message queryReq {
string id = 1;
string parameters = 2;
}
message objectRes {
// what should I write here?
}
I know I can set the result as a string, and just stringify the whole object, but is that the intended way? Is there not a better (and more 'correct') way to do this? Or shall I return a (maybe) big ass string each time? It seems a bit suboptimal.
The simplest option would indeed be to just stringify the object on the server and reverse the process on the client.
One possible alternative would be to use the google.protobuf.Struct
message type, which can represent arbitrary JSON-equivalent objects. Unfortunately, that type isn't automatically transformed into (or from) regular JavaScript objects, so you'd have to work with the actual value objects. Plus, you should keep in mind that the entire structure of the message has to be stored when using the Struct
type, so you can't even expect it to be significantly smaller than the JSON representation.