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 {
required string id = 1;
string value = 2;
}
Using .proto files
import protobuf from 'protocol-buffers';
import Codec from '@dxos/codec-protobuf';
const codec = new Codec({ verify: true });
(async () => {
const schema = await protobufjs.load('schema.proto')
codec.load(schema);
const buffer = codec.encode({ type: 'Task', message: { id: 'task-0', value: 'test' } });
codec.decode(buffer);
})();
Using JSON descriptors
import protobuf from 'protocol-buffers';
import Codec from '@dxos/codec-protobuf';
const codec = new Codec({ verify: true });
codec.loadFromJSON(require('./schema.json'));
const buffer = codec.encode({ type: 'Task', message: { id: 'task-0', value: 'test' } });
codec.decode(buffer);
API
const codec = new Codec([options])
Create a new CodecProtobuf instance.
The options are:
verify: boolean
: Enable the message validation. Default: false
.decodeWithType: boolean
: Define if the decode operation should return { type, message }
or just message
. Default: true
.
codec.load(root) -> codec
Add a schema from a root Namespace object.
codec.fromJSON(json) -> codec
Add a schema from a JSON object or their string representation.
codec.getType(type) -> (Type|null)
Get a type from the loaded schemas.
codec.encode(data) -> Buffer
Encode an object using a specific protobuf type.
data: Object
type: string
Type for the encoding.message: Any
Message to encode.
codec.decode(buffer, withType) -> Message
buffer: Buffer
withType: boolean
Default: true
Message could return { type, message }
using withType
or just the message
.
Contributing
PRs accepted.
License
GPL-3.0 © dxos