|
| 1 | +/* |
| 2 | + * |
| 3 | + * Copyright 2025 gRPC authors. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + * |
| 17 | + */ |
| 18 | + |
| 19 | +const grpc = require('@grpc/grpc-js'); |
| 20 | +const protoLoader = require('@grpc/proto-loader'); |
| 21 | +const parseArgs = require('minimist'); |
| 22 | + |
| 23 | +const PROTO_PATH = __dirname + '/../protos/echo.proto'; |
| 24 | + |
| 25 | +const packageDefinition = protoLoader.loadSync( |
| 26 | + PROTO_PATH, |
| 27 | + {keepCase: true, |
| 28 | + longs: String, |
| 29 | + enums: String, |
| 30 | + defaults: true, |
| 31 | + oneofs: true |
| 32 | + }); |
| 33 | +const echoProto = grpc.loadPackageDefinition(packageDefinition).grpc.examples.echo; |
| 34 | + |
| 35 | +const serviceConfig = { |
| 36 | + loadBalancingConfig: [], |
| 37 | + methodConfig: [ |
| 38 | + { |
| 39 | + name: [ |
| 40 | + { |
| 41 | + service: 'grpc.examples.echo.Echo', |
| 42 | + }, |
| 43 | + ], |
| 44 | + retryPolicy: { |
| 45 | + maxAttempts: 4, |
| 46 | + initialBackoff: '0.01s', |
| 47 | + maxBackoff: '0.01s', |
| 48 | + backoffMultiplier: 1.0, |
| 49 | + retryableStatusCodes: ['UNAVAILABLE'], |
| 50 | + }, |
| 51 | + }, |
| 52 | + ], |
| 53 | +}; |
| 54 | + |
| 55 | +function main() { |
| 56 | + let argv = parseArgs(process.argv.slice(2), { |
| 57 | + string: 'target', |
| 58 | + default: {target: 'localhost:50052'} |
| 59 | + }); |
| 60 | + |
| 61 | + // Set up a connection to the server with service config and create the channel. |
| 62 | + // However, the recommended approach is to fetch the retry configuration |
| 63 | + // (which is part of the service config) from the name resolver rather than |
| 64 | + // defining it on the client side. |
| 65 | + const client = new echoProto.Echo('localhost:50052', grpc.credentials.createInsecure(), { 'grpc.service_config': JSON.stringify(serviceConfig) }); |
| 66 | + client.unaryEcho({message: 'Try and Success'}, (error, value) => { |
| 67 | + if (error) { |
| 68 | + console.log(`Unexpected error from UnaryEcho: ${error}`); |
| 69 | + return; |
| 70 | + } |
| 71 | + console.log(`RPC response: ${JSON.stringify(value)}`); |
| 72 | + }); |
| 73 | +} |
| 74 | + |
| 75 | +main(); |
0 commit comments