Skip to content

Commit

Permalink
Merge pull request #2474 from murgatroid99/import_examples
Browse files Browse the repository at this point in the history
Import examples from core repository
  • Loading branch information
murgatroid99 committed Jun 22, 2023
2 parents 186718c + 204cd38 commit 3098d69
Show file tree
Hide file tree
Showing 27 changed files with 4,462 additions and 0 deletions.
49 changes: 49 additions & 0 deletions examples/README.md
@@ -0,0 +1,49 @@
gRPC in 3 minutes (Node.js)
===========================

PREREQUISITES
-------------

- `node`: This requires Node 8.13.0 or greater.

INSTALL
-------

```sh
$ # Get the gRPC repository
$ export REPO_ROOT=grpc-node # REPO root can be any directory of your choice
$ git clone -b RELEASE_TAG_HERE https://github.com/grpc/grpc-node $REPO_ROOT
$ cd $REPO_ROOT

$ cd examples
$ npm install
```

TRY IT!
-------

There are two ways to generate the code needed to work with protocol buffers in Node.js - one approach uses [Protobuf.js](https://github.com/dcodeIO/ProtoBuf.js/) to dynamically generate the code at runtime, the other uses code statically generated using the protocol buffer compiler `protoc`. The examples behave identically, and either server can be used with either client.

- Run the server

```sh
$ # from this directory
$ node ./helloworld/dynamic_codegen/greeter_server.js &
$ # OR
$ node ./helloworld/static_codegen/greeter_server.js &
```

- Run the client

```sh
$ # from this directory
$ node ./helloworld/dynamic_codegen/greeter_client.js
$ # OR
$ node ./helloworld/static_codegen/greeter_client.js
```

TUTORIAL
--------
You can find a more detailed tutorial in [gRPC Basics: Node.js][]

[gRPC Basics: Node.js]:https://grpc.io/docs/languages/node/basics
57 changes: 57 additions & 0 deletions examples/helloworld/dynamic_codegen/greeter_client.js
@@ -0,0 +1,57 @@
/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

var PROTO_PATH = __dirname + '/../../protos/helloworld.proto';

var parseArgs = require('minimist');
var grpc = require('@grpc/grpc-js');
var protoLoader = require('@grpc/proto-loader');
var packageDefinition = protoLoader.loadSync(
PROTO_PATH,
{keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
});
var hello_proto = grpc.loadPackageDefinition(packageDefinition).helloworld;

function main() {
var argv = parseArgs(process.argv.slice(2), {
string: 'target'
});
var target;
if (argv.target) {
target = argv.target;
} else {
target = 'localhost:50051';
}
var client = new hello_proto.Greeter(target,
grpc.credentials.createInsecure());
var user;
if (argv._.length > 0) {
user = argv._[0];
} else {
user = 'world';
}
client.sayHello({name: user}, function(err, response) {
console.log('Greeting:', response.message);
});
}

main();
52 changes: 52 additions & 0 deletions examples/helloworld/dynamic_codegen/greeter_server.js
@@ -0,0 +1,52 @@
/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

var PROTO_PATH = __dirname + '/../../protos/helloworld.proto';

var grpc = require('@grpc/grpc-js');
var protoLoader = require('@grpc/proto-loader');
var packageDefinition = protoLoader.loadSync(
PROTO_PATH,
{keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
});
var hello_proto = grpc.loadPackageDefinition(packageDefinition).helloworld;

/**
* Implements the SayHello RPC method.
*/
function sayHello(call, callback) {
callback(null, {message: 'Hello ' + call.request.name});
}

/**
* Starts an RPC server that receives requests for the Greeter service at the
* sample server port
*/
function main() {
var server = new grpc.Server();
server.addService(hello_proto.Greeter.service, {sayHello: sayHello});
server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), () => {
server.start();
});
}

main();
7 changes: 7 additions & 0 deletions examples/helloworld/static_codegen/README.md
@@ -0,0 +1,7 @@
This is the static code generation variant of the Hello World. Code in these examples is pre-generated using protoc and the Node gRPC protoc plugin, and the generated code can be found in various `*_pb.js` files. The command line sequence for generating those files is as follows (assuming that `protoc` and `grpc_node_plugin` are present, and starting in the directory which contains this README.md file):

```sh
cd ../protos
npm install -g grpc-tools
grpc_tools_node_protoc --js_out=import_style=commonjs,binary:../helloworld/static_codegen/ --grpc_out=grpc_js:../helloworld/static_codegen/ helloworld.proto
```
50 changes: 50 additions & 0 deletions examples/helloworld/static_codegen/greeter_client.js
@@ -0,0 +1,50 @@
/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

var parseArgs = require('minimist');
var messages = require('./helloworld_pb');
var services = require('./helloworld_grpc_pb');

var grpc = require('@grpc/grpc-js');

function main() {
var argv = parseArgs(process.argv.slice(2), {
string: 'target'
});
var target;
if (argv.target) {
target = argv.target;
} else {
target = 'localhost:50051';
}
var client = new services.GreeterClient(target,
grpc.credentials.createInsecure());
var request = new messages.HelloRequest();
var user;
if (argv._.length > 0) {
user = argv._[0];
} else {
user = 'world';
}
request.setName(user);
client.sayHello(request, function(err, response) {
console.log('Greeting:', response.getMessage());
});
}

main();
45 changes: 45 additions & 0 deletions examples/helloworld/static_codegen/greeter_server.js
@@ -0,0 +1,45 @@
/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

var messages = require('./helloworld_pb');
var services = require('./helloworld_grpc_pb');

var grpc = require('@grpc/grpc-js');

/**
* Implements the SayHello RPC method.
*/
function sayHello(call, callback) {
var reply = new messages.HelloReply();
reply.setMessage('Hello ' + call.request.getName());
callback(null, reply);
}

/**
* Starts an RPC server that receives requests for the Greeter service at the
* sample server port
*/
function main() {
var server = new grpc.Server();
server.addService(services.GreeterService, {sayHello: sayHello});
server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), () => {
server.start();
});
}

main();
61 changes: 61 additions & 0 deletions examples/helloworld/static_codegen/helloworld_grpc_pb.js
@@ -0,0 +1,61 @@
// GENERATED CODE -- DO NOT EDIT!

// Original file comments:
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
'use strict';
var grpc = require('@grpc/grpc-js');
var helloworld_pb = require('./helloworld_pb.js');

function serialize_helloworld_HelloReply(arg) {
if (!(arg instanceof helloworld_pb.HelloReply)) {
throw new Error('Expected argument of type helloworld.HelloReply');
}
return Buffer.from(arg.serializeBinary());
}

function deserialize_helloworld_HelloReply(buffer_arg) {
return helloworld_pb.HelloReply.deserializeBinary(new Uint8Array(buffer_arg));
}

function serialize_helloworld_HelloRequest(arg) {
if (!(arg instanceof helloworld_pb.HelloRequest)) {
throw new Error('Expected argument of type helloworld.HelloRequest');
}
return Buffer.from(arg.serializeBinary());
}

function deserialize_helloworld_HelloRequest(buffer_arg) {
return helloworld_pb.HelloRequest.deserializeBinary(new Uint8Array(buffer_arg));
}


// The greeting service definition.
var GreeterService = exports.GreeterService = {
// Sends a greeting
sayHello: {
path: '/helloworld.Greeter/SayHello',
requestStream: false,
responseStream: false,
requestType: helloworld_pb.HelloRequest,
responseType: helloworld_pb.HelloReply,
requestSerialize: serialize_helloworld_HelloRequest,
requestDeserialize: deserialize_helloworld_HelloRequest,
responseSerialize: serialize_helloworld_HelloReply,
responseDeserialize: deserialize_helloworld_HelloReply,
},
};

exports.GreeterClient = grpc.makeGenericClientConstructor(GreeterService);

0 comments on commit 3098d69

Please sign in to comment.