LoginSignup
0
2

More than 3 years have passed since last update.

JavaScriptでProtocol Buffersを使う(protobuf.js)

Last updated at Posted at 2020-08-15

画面(JavaScript)からProtocol Buffersを使う機会があったので、メモしておきます。
OSSは、protobufjs/protobuf.jsを利用しました。
https://github.com/protobufjs/protobuf.js

demo

※ サンプルコード全量
https://github.com/Thirosue/protocol-buffers-javascript-sample

インターフェイス定義

インターフェース定義は公式のサンプルを利用します。
この定義は、インターネットで取得できる場所に配置しておきます。

person.proto
syntax = "proto3";
package person;

message Person {
  string name = 1;
  uint32 id = 2;
  string email = 3;
}

CDN

以下から、スクリプトを取得します。
https://www.jsdelivr.com/package/npm/protobufjs

<script src="https://cdn.jsdelivr.net/npm/protobufjs@6.10.1/dist/protobuf.min.js"></script>

サンプルコード

      protobuf.load("person.proto", function (err, root) {
        if (err) throw err;

        // インターフェース定義を取得する
        var Person = root.lookupType("person.Person");

        // 設定するデータを定義
        var payload = {
          name: "john doe",
          id: 99,
          email: "test@example.com",
        };

        // データを検証
        var errMsg = Person.verify(payload);
        if (errMsg) throw Error(errMsg);

        // 連携するメッセージを作成する
        var person = Person.create(payload);
        console.log(new TextDecoder().decode(buffer)); // 文字列に変換する
        console.log(btoa(String.fromCharCode(...buffer))); // base64エンコード

        // メッセージを Uint8Array に変換する
        var buffer = Person.encode(person).finish();

        // メッセージをデコードする
        var person = Person.decode(buffer);

        // メッセージをオブジェクトに変換する
        var object = Person.toObject(person, {
          longs: String,
          enums: String,
          bytes: String,
          // see ConversionOptions
        });
      });
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2