google protobuf-js : 如何有效地解析我的消息

google protobuf-js : How to parse efficiently my messages

我正在开发 Angular5+ 前端,它使用 google-protobuf JS 和 WebSocket 与后端通信。

我的 .proto 文件中目前有 2 个对象:

然后我制作了一个处理程序服务,它将获取通过 WebSocket 发送的消息,但后来我遇到了一个大问题:我找不到有效解析/反序列化我的对象的方法:

this._socketService.getSocket().onmessage = ((message: Message) => {
  const uiArray = new Uint8Array(message.data);
  this.parseMessage(uiArray);
});

parseMessage(uiArray: Uint8Array) {
  let response = null;

  // DOES NOT WORK
  // response = reqRep.Response.deserializeBinary(uiArray) || notif.BackendStatusNotification.deserializeBinary(uiArray);

  // <==== This is where I need to find a good way to deserialize efficiently my objects
  // TEMPORARY
  if (uiArray.byteLength === 56) {
    response = reqRep.Response.deserializeBinary(uiArray)
  } else {
    response = notif.BackendStatusNotification.deserializeBinary(uiArray);
  }

  // Notify different Observables which object has changed based on their type
  switch (response && response.hasSupplement() && response.getSupplement().array[0]) {
    case 'type.googleapis.com/req.BackendStatusResponse':
       this._responseSubject.next(response);
       break;
     case 'type.googleapis.com/notif.BackendStatusNotification':
       this._notificationSubject.next(response);
       break;
     default:
       console.log('DOESN\'T WORK');
   }
}

我尝试使用代码中所示的 || 来始终能够反序列化我的响应,但它不起作用:如果第一个失败,我会收到运行时错误。

我有一些见解,但也许有人可以帮助我:

最后,我做了我在问题中提到的最后一个选项,即将我所有的不同对象封装在一个通用对象中。

这样,我只有一种方法来反序列化我的对象,然后分派对嵌套已知对象的处理。它完美运行。