Skip to content

Commit

Permalink
Added service example to README, see #529 [ci skip]
Browse files Browse the repository at this point in the history
  • Loading branch information
dcodeIO committed Dec 8, 2016
1 parent 9bdec62 commit 228a202
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,44 @@ var message = new AwesomeMessage({ awesomeField: "AwesomeString" });

Custom classes are automatically populated with static `encode`, `encodeDelimited`, `decode`, `decodeDelimited` and `verify` methods and reference their reflected type via the `$type` property. Note that there are no methods (just `$type`) on instances by default as method names might conflict with field names.

### Using services

```protobuf
// greeter.proto
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
```

```js
...
var Greeter = root.lookup("Greeter");
var greeter = Greeter.create(rpcImpl);

greeter.sayHello({ name: 'you' }, function(err, response) {
console.log('Greeting:', response.message);
});
```

To make this work, all you have to do is provide an `rpcImpl`, which is is an asynchronous function that takes the reflected service method, the binary HelloRequest and a node-style callback as its parameters. For example:

```js
function rpcImpl(method, requestData, callback) {
// perform the request using an HTTP request or a WebSocket for example
var responseData = ...;
// and call the callback with the binary response afterwards:
callback(null, responseData);
}
```

### Usage with TypeScript

```ts
Expand Down
6 changes: 5 additions & 1 deletion src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,11 @@ util.asPromise = asPromise;
function fetch(path, callback) {
if (!callback)
return asPromise(fetch, util, path);
try { return eval(['req','uire'].join(''))("fs").readFile(path, "utf8", callback); } catch (e) { } // eslint-disable-line no-empty, no-eval
try {
// Hide this from webpack. There is probably another, better way.
return eval(['req','uire'].join(''))("fs") // eslint-disable-line no-eval
.readFile(path, "utf8", callback);
} catch (e) { } // eslint-disable-line no-empty
var xhr = new XMLHttpRequest();
function onload() {
if (xhr.status !== 0 && xhr.status !== 200)
Expand Down

0 comments on commit 228a202

Please sign in to comment.