How to convert object to protobuf data in nodejs

580 views Asked by At

If I have a proto3 message defined as below

message Log {
  string object = 1;
  string key_result = 2;
  string review = 3;
  repeated string tag = 4;

  string begin_at = 5;
  string end_at = 6;
  string created_at = 7;
  string id = 8;
}

the protoc with --js_out and --ts_out will generate dts like

export class Log extends jspb.Message {
  getObject(): string;
  setObject(value: string): void;

  getKeyResult(): string;
  setKeyResult(value: string): void;

  getReview(): string;
  setReview(value: string): void;

  clearTagList(): void;
  getTagList(): Array<string>;
  setTagList(value: Array<string>): void;
  addTag(value: string, index?: number): string;

  getBeginAt(): string;
  setBeginAt(value: string): void;

  getEndAt(): string;
  setEndAt(value: string): void;

  getCreatedAt(): string;
  setCreatedAt(value: string): void;

  getId(): string;
  setId(value: string): void;

  serializeBinary(): Uint8Array;
  toObject(includeInstance?: boolean): Log.AsObject;
  static toObject(includeInstance: boolean, msg: Log): Log.AsObject;
  static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
  static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
  static serializeBinaryToWriter(message: Log, writer: jspb.BinaryWriter): void;
  static deserializeBinary(bytes: Uint8Array): Log;
  static deserializeBinaryFromReader(message: Log, reader: jspb.BinaryReader): Log;
}

It is simple to convert Log class to Object via toObject method. But to convert the object to the class, i need to set each field manually.

export function toLog(log: Log.AsObject): Log {
    const t = new Log
    t.setObject(log.object)
    t.setKeyResult(log.keyResult)
    t.setReview(log.review)
    t.setTagList(log.tagList)
    t.setBeginAt(log.beginAt)
    t.setEndAt(log.endAt)
    t.setCreatedAt(log.createdAt)
    t.setId(log.id)
    return t
}

Do any simpler way to perform such a task?

0

There are 0 answers