Codec Protobuf
Codec for protobuf to use in libraries that follows the valueEncoding API of leveldb, like hypercore.
This module use a custom implementation of protobuf.js to support decode Buffer
s in the browser.
Install
$ npm install @dxos/codec-protobuf
Usage
syntax = "proto3";
message Task {
string id = 1;
string title = 2;
}
Using .proto files
import protobufjs from 'protobufjs';
import { Codec } from '@dxos/codec-protobuf';
const codec = new Codec('Task');
(async () => {
codec
.addJson(await protobufjs.load('schema.proto'))
.build();
const buffer = codec.encode({ id: 'task-0', title: 'test' });
codec.decode(buffer);
})();
Using JSON descriptors
import protobufjs from 'protobufjs';
import { Codec } from '@dxos/codec-protobuf';
const codec = new Codec('Task');
codec
.addJson(require('./schema.json'))
.build();
const buffer = codec.encode({ id: 'task-0', title: 'test' });
codec.decode(buffer);
API
const codec = new Codec(rootTypeUrl, [options])
Create a new CodecProtobuf instance.
The options are:
rootTypeUrl: string
: Defines the root type message to encode/decode messages. Required.options: Object
recursive: boolean
: Recursively decode the buffer. Default: true
.strict: boolean
: Throw an exception if the type is not found. Default: true
.
codec.addJson(json) -> codec
Add the given JSON schema to the type dictionary.
codec.getType(type) -> (Type|null)
Get a type from the loaded schemas.
type: string
: Fully qualified type name.
codec.encode(data) -> Buffer
Encode an object using a specific protobuf type.
codec.decode(buffer) -> Object
Contributing
PRs accepted.
License
GPL-3.0 © dxos