1
0

enum.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. "use strict";
  2. // Copyright 2021 Google LLC
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. Object.defineProperty(exports, "__esModule", { value: true });
  16. exports.resolveEnumValueToNumber = exports.resolveEnumValueToString = void 0;
  17. function resolveEnumValueToString(enumType, enumValue) {
  18. // for unknown enum values, do not fail and try to do the best we could.
  19. // protobuf.js fromObject() will likely ignore unknown values, but at least
  20. // we won't fail.
  21. if (typeof enumValue === 'number') {
  22. const value = enumType.valuesById[enumValue];
  23. if (typeof value === 'undefined') {
  24. // unknown value, cannot convert to string, returning number as is
  25. return enumValue;
  26. }
  27. return value;
  28. }
  29. if (typeof enumValue === 'string') {
  30. // for strings, just accept what we got
  31. return enumValue;
  32. }
  33. throw new Error('resolveEnumValueToString: enum value must be a string or a number');
  34. }
  35. exports.resolveEnumValueToString = resolveEnumValueToString;
  36. function resolveEnumValueToNumber(enumType, enumValue) {
  37. if (typeof enumValue === 'number') {
  38. // return as is
  39. return enumValue;
  40. }
  41. if (typeof enumValue === 'string') {
  42. const num = enumType.values[enumValue];
  43. if (typeof num === 'undefined') {
  44. // unknown value, cannot convert to number, returning string as is
  45. return enumValue;
  46. }
  47. return num;
  48. }
  49. throw new Error('resolveEnumValueToNumber: enum value must be a string or a number');
  50. }
  51. exports.resolveEnumValueToNumber = resolveEnumValueToNumber;
  52. //# sourceMappingURL=enum.js.map