Protobuf NodeJS Проблема декодирования кодирования - PullRequest
0 голосов
/ 13 июля 2020

Я использую пакет protobuf js node для работы с protobuf. В моей файловой структуре protobuf у меня есть 3 внутренних типа сообщения protobuf. Это моя файловая структура protobuf:

message OuterMessage {
  int32 customer_id = 1;

  ...

  entity.InnerMessage inner_message = 3;
  repeated SecondInnerMessage second_message = 4;
}

message InnerMessage {
  int32 customer_id = 1;

  ...

  google.protobuf.Timestamp start_date_time = 3;
  google.protobuf.Timestamp end_date_time = 4;
}

message SecondInnerMessage {
  int32 customer_id = 1;

  ...

  message ThirdInnerMessage {
    int32 attr = 1;
  }

  ThirdInnerMessage third = 8;
}

message Envelope {
  int32 envelope_version = 1; 

 ...

  google.protobuf.Any payload = 100;
}

В основном внешнее сообщение находится внутри конверта. Вот как я читаю файлы protobuf:

protobuf.load(filePath, function (err, root) {
            if (err)
                throw err;

            // Obtain a message type
            messageType = root.lookupType("...Envelope");

            // Verify the payload if necessary (i.e. when possibly incomplete or invalid)
            // Here the payload is a json object in the same structure with Envelope
            errMsg = messageType.verify(JSON.parse(JSON.stringify(payload)));
            if (errMsg)
                throw Error(errMsg);

            // create message instance
            let envelope = messageType.create(JSON.parse(JSON.stringify(payload)));
            console.log(envelope);
            let encoded = messageType.encode(envelope).finish();
            console.log("Encoded ", encoded);
            let decoded = messageType.decode(encoded);
            console.log("Decoded: ", decoded);
            resolve(encoded);
        });

Вывод приведенного выше кода (я удалил имена атрибутов и поставил только attr):

Envelope {
  attr: 123,
  attr: 1594650602645,
  payload: 
   { attr2: 1,
     attr3: 2,
     outer_message: 
      { attr: 1,
        attr: 3,
        attr: '2020-05-05 00:00:00',
        attr: '2020-06-05 00:00:00' },
     second_message: [ [Object] ] } }
Encoded  <Buffer a2 06 00>
<Buffer a2 06 00>
Decoded:  Envelope { payload: Any {} }

У меня пара проблем с этим кодом. Во-первых, конверт печатается неправильно. Часть SecondInnerMessage печатает только [ [Object] ], даже если она заполнена данными.

Во-вторых, даже несмотря на то, что имеется довольно большой объем данных, закодированная версия - это просто <Buffer a2 06 00> <Buffer a2 06 00>. Это верно? Почему он слишком короткий?

В-третьих, в декодированной версии я не могу вернуть данные. Он просто печатает пустую полезную нагрузку. Почему это?

...