|
1 | 1 | // this example demonstrates a way to keep field casing (as defined within .proto files) |
2 | 2 | // while still having virtual getters and setters for the camel cased counterparts. |
3 | 3 |
|
| 4 | +/*eslint-disable strict, no-console*/ |
4 | 5 | var protobuf = require(".."); |
5 | 6 |
|
6 | 7 | var proto = "syntax=\"proto3\";\ |
7 | 8 | message MyMessage {\ |
8 | 9 | string some_field = 1;\ |
9 | 10 | }"; |
10 | 11 |
|
11 | | -var root = protobuf.parse(proto, { keepCase: true }).root; |
| 12 | +var root = protobuf.parse(proto, { keepCase: true }).root; // or use Root#load |
12 | 13 |
|
13 | | -function camelCase(str) { |
| 14 | +function toCamelCase(str) { |
14 | 15 | return str.substring(0,1) + str.substring(1).replace(/_([a-z])(?=[a-z]|$)/g, function($0, $1) { return $1.toUpperCase(); }); |
15 | 16 | } |
16 | 17 |
|
| 18 | +function addAliasProperty(type, name, aliasName) { |
| 19 | + if (aliasName !== name) |
| 20 | + Object.defineProperty(type.ctor.prototype, aliasName, { |
| 21 | + get: function() { return this[name]; }, |
| 22 | + set: function(value) { this[name] = value; } |
| 23 | + }); |
| 24 | +} |
| 25 | + |
17 | 26 | // this function adds alternative getters and setters for the camel cased counterparts |
18 | 27 | // to the runtime message's prototype (i.e. without having to register a custom class): |
19 | 28 | function addVirtualCamelcaseFields(type) { |
20 | 29 | 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 | | - }); |
| 30 | + addAliasProperty(type, field.name, toCamelCase(field.name)); |
31 | 31 | }); |
| 32 | + type.oneofsArray.forEach(function(oneof) { |
| 33 | + addAliasProperty(type, oneof.name, toCamelCase(oneof.name)); |
| 34 | + }); |
| 35 | + return type; |
32 | 36 | } |
33 | 37 |
|
34 | | -var MyMessage = root.lookup("MyMessage"); |
35 | | - |
36 | | -addVirtualCamelcaseFields(MyMessage); |
| 38 | +var MyMessage = addVirtualCamelcaseFields(root.lookup("MyMessage")); |
37 | 39 |
|
38 | 40 | var myMessage = MyMessage.create({ |
39 | 41 | some_field /* or someField */: "hello world" |
|
0 commit comments