Skip to content

Commit 228a202

Browse files
committed
Added service example to README, see #529 [ci skip]
1 parent 9bdec62 commit 228a202

2 files changed

Lines changed: 43 additions & 1 deletion

File tree

README.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,44 @@ var message = new AwesomeMessage({ awesomeField: "AwesomeString" });
165165

166166
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.
167167

168+
### Using services
169+
170+
```protobuf
171+
// greeter.proto
172+
service Greeter {
173+
rpc SayHello (HelloRequest) returns (HelloReply) {}
174+
}
175+
176+
message HelloRequest {
177+
string name = 1;
178+
}
179+
180+
message HelloReply {
181+
string message = 1;
182+
}
183+
```
184+
185+
```js
186+
...
187+
var Greeter = root.lookup("Greeter");
188+
var greeter = Greeter.create(rpcImpl);
189+
190+
greeter.sayHello({ name: 'you' }, function(err, response) {
191+
console.log('Greeting:', response.message);
192+
});
193+
```
194+
195+
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:
196+
197+
```js
198+
function rpcImpl(method, requestData, callback) {
199+
// perform the request using an HTTP request or a WebSocket for example
200+
var responseData = ...;
201+
// and call the callback with the binary response afterwards:
202+
callback(null, responseData);
203+
}
204+
```
205+
168206
### Usage with TypeScript
169207

170208
```ts

src/util.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,11 @@ util.asPromise = asPromise;
9898
function fetch(path, callback) {
9999
if (!callback)
100100
return asPromise(fetch, util, path);
101-
try { return eval(['req','uire'].join(''))("fs").readFile(path, "utf8", callback); } catch (e) { } // eslint-disable-line no-empty, no-eval
101+
try {
102+
// Hide this from webpack. There is probably another, better way.
103+
return eval(['req','uire'].join(''))("fs") // eslint-disable-line no-eval
104+
.readFile(path, "utf8", callback);
105+
} catch (e) { } // eslint-disable-line no-empty
102106
var xhr = new XMLHttpRequest();
103107
function onload() {
104108
if (xhr.status !== 0 && xhr.status !== 200)

0 commit comments

Comments
 (0)