Source: client/parser/object-parser.js

  1. /*
  2. * Copyright 2023, TeamDev. All rights reserved.
  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. * Redistribution and use in source and/or binary forms, with or without
  11. * modification, must retain the above copyright notice and the following
  12. * disclaimer.
  13. *
  14. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  15. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  16. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  17. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  18. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  19. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  20. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. "use strict";
  27. import {Message} from 'google-protobuf';
  28. /**
  29. * Parses a plain Javascript object to a Protobuf message.
  30. *
  31. * The class is abstract and should be implemented for every message type.
  32. */
  33. export default class ObjectParser {
  34. /**
  35. * Creates a new instance.
  36. */
  37. constructor() {
  38. if (this.constructor === ObjectParser) {
  39. throw new Error('Cannot instantiate abstract ObjectParser class.');
  40. }
  41. }
  42. /**
  43. * Converts an object to a message.
  44. *
  45. * @abstract
  46. * @param {!Object} object the object representing a Protobuf message
  47. * @return {!Message} the parsed Protobuf message
  48. */
  49. fromObject(object) {
  50. throw new Error('The method is abstract and should be implemented by a subclass');
  51. }
  52. /**
  53. * Checks if the parser extends {@link ObjectParser}.
  54. *
  55. * <p>The implementation doesn't use `instanceof` check and check on prototypes
  56. * since they may fail if different versions of the file are used at the same time
  57. * (e.g. bundled and the original one).
  58. *
  59. * @param object the object to check
  60. */
  61. static isParser(object) {
  62. const abstractMethod = object.fromObject;
  63. const methodDefined = typeof abstractMethod === 'function';
  64. return methodDefined;
  65. }
  66. }