Reputation: 527
I'm planning to implement a basic nodejs project where I will have 3 services:
Product and Order will do pretty much the what their name suggests and gateway will take json request parse it to proto objects and make rpc calls to appropriate microservice.
Here is one of the service that i have written:
service CoreService {
rpc AddProduct(AddProductRequest) returns (AddProductResponse);
}
message AddProductRequest {
product.Product product = 1;
}
message AddProductResponse {
product.Product product = 1;
}
For each service I have already compiled the proto files using the ts-proto
package.
Quite new to grpc so want to clear confusing about a few things:
After compiling the proto files using ts-proto
I got a method called fromJson
which I think is for converting JSON objects to proto objects(?). With this in mind I created an endpoint:
router.post('/AddProduct', (req, res) => {
const product = Product.fromJSON(req.body);
});
But what confuses me is my gateway is an express application(since I want JSON request), but shouldn't it be a grpc client?
index.ts for Product:
const server = new grpc.Server();
server.bindAsync(
"localhost:8081",
grpc.ServerCredentials.createInsecure(),
(err, port) => {
if (err) {
console.error(err);
return;
}
console.log(`Server listening on ${port}`);
server.start();
}
);
If I am on right track how can I make a rpc call to Product microservice and send the product object from my gateway microservice(which is an express application)?
I know JSON to proto is possible in Java and go but is it possible to do what I want in nodejs and typescript?
Upvotes: 1
Views: 780
Reputation: 40061
Protobuf (proto3) supports JSON-encoding of messages (e.g. toJSON
, fromJSON
) to facilitate what you describe.
Servers commonly are clients to other services too.
In your case, Gateway
exposes a REST service and its implementation needs to interact with Product
and Order
which you're choosing to implement as gRPC services.
One way (!?) to do this is to embed gRPC client(s) in Gateway
to make the requests against the Product
and Order
services. This is called tight-coupling.
Another (!) way you could do this would be to use some form of message broker, in which Gateway
publishes Product
and Order
messages to queues on the broker and your Product
and Order
services subscribe to the relevant queues to retrieve messages.This is known as loose-coupling.
Tightly-coupled and loosely-coupled services may interact using HTTP/REST, gRPC or other protocols.
Upvotes: 2