Skip to content

Commit 8eeffcb

Browse files
committed
Other: Added a custom getters/setters example for gRPC
1 parent 478ee51 commit 8eeffcb

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

examples/custom-get-set.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// this example demonstrates a way to keep field casing (as defined within .proto files)
2+
// while still having virtual getters and setters for the camel cased counterparts.
3+
4+
var protobuf = require("..");
5+
6+
var proto = "syntax=\"proto3\";\
7+
message MyMessage {\
8+
string some_field = 1;\
9+
}";
10+
11+
var root = protobuf.parse(proto, { keepCase: true }).root;
12+
13+
function camelCase(str) {
14+
return str.substring(0,1) + str.substring(1).replace(/_([a-z])(?=[a-z]|$)/g, function($0, $1) { return $1.toUpperCase(); });
15+
}
16+
17+
// this function adds alternative getters and setters for the camel cased counterparts
18+
// to the runtime message's prototype (i.e. without having to register a custom class):
19+
function addVirtualCamelcaseFields(type) {
20+
type.fieldsArray.forEach(function(field) {
21+
var altName = camelCase(field.name);
22+
if (altName !== field.name)
23+
Object.defineProperty(type.ctor.prototype, altName, {
24+
get: function() {
25+
return this[field.name];
26+
},
27+
set: function(value) {
28+
this[field.name] = value;
29+
}
30+
});
31+
});
32+
}
33+
34+
var MyMessage = root.lookup("MyMessage");
35+
36+
addVirtualCamelcaseFields(MyMessage);
37+
38+
var myMessage = MyMessage.create({
39+
some_field /* or someField */: "hello world"
40+
});
41+
42+
console.log(
43+
"someField:", myMessage.someField,
44+
"\nsome_field:", myMessage.some_field,
45+
"\nJSON:", JSON.stringify(myMessage)
46+
);

0 commit comments

Comments
 (0)