1.0.0 • Published 3 months ago

tsprotobuf-codec v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
3 months ago

tsprotobuf-codec

A browser-compatible protocol buffer encoder/decoder in typescript

Using

Note: this package is designed to be used from code generated by a protocol buffer code generator, but it can be used in any low-level library or to dynamically construct any arbitrary protocol buffer message. The example here shows one way of doing that.

yarn add tsprotobuf-codec

This provides read and write functions for translating between the wire format and javascript representation of the various proto3 types, such as int32, double, fixed32, etc..

So if you had a protocol buffer that looked something like this:

message MyMessage {
    int32 my_number = 1;
    string my_string = 2;
}

Then you could write that with the following code (normally raw access like this would be through generated code)

  import {WriteField as write, allocateNestingWriter, arrayCollector} from "tsprotobuf-codec";

  const myNumber = 42;
  const myNumber_field = 1;

  const myString = "The ultimate answer";
  const myString_field = 2;

  // Preallocate a buffer
  const writer = allocateNestingWriter(1024);

  // Write the fields to the buffer
  write.int32(writer, myNumber, myNumber_field);
  write.string(writer, myString, myString_field);

  // and then get the resulting blob
  const encoded = writer.finish(arrayCollector);

Building

yarn install
yarn test
1.0.0

3 months ago