Skip to content

Instantly share code, notes, and snippets.

@jefferyshivers
Created March 21, 2020 19:09
Show Gist options
  • Save jefferyshivers/7fd4af9ab163533100ab6db66c581d77 to your computer and use it in GitHub Desktop.
Save jefferyshivers/7fd4af9ab163533100ab6db66c581d77 to your computer and use it in GitHub Desktop.
Example gRPC client in Node
const PROTO_PATH = __dirname + '/.protop/path/awesomelabs/numbers/money.proto';
const grpc = require('grpc');
const protoLoader = require('@grpc/proto-loader');
const packageDefinition = protoLoader.loadSync(PROTO_PATH, { keepCase: true, enums: String });
const protoDescriptor = grpc.loadPackageDefinition(packageDefinition);
const numbers = protoDescriptor.awesomelabs.numbers;
const moneyServiceStub = new numbers.MoneyService('localhost:8080', grpc.credentials.createInsecure());
// Create a request
const originalMoney = {
currency: "USD",
units: Math.random() * 10
};
const targetCurrency = 'MXN';
const convertMoneyRequest = {
original: originalMoney,
target_currency: targetCurrency
};
// Call the MoneyService "convert" method
moneyServiceStub.convert(convertMoneyRequest, (err, result) => {
if (err) {
console.error(err)
} else {
console.log(`Original: ${originalMoney.units} ${originalMoney.currency}`)
console.log(`Converted: ${result.units} ${result.currency}`)
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment