Skip to content
This repository was archived by the owner on Nov 28, 2019. It is now read-only.

elderapo/protobuf-lite

@elderapo/protobuf-lite

styled with prettier Greenkeeper badge Build Status AppVeyor Coveralls Dev Dependencies FOSSA Status

Minimalistic library for easy, fast and optimal serialization/deserialization of data to binary format. Under the hood uses dcodeIO/protobuf.js and some magic 🧙.

Mainly was created because dcodeIO/protobuf.js requires a lot of boilerplate and doesn't support native js Date object serialization/deserialization. It recovers all the prototypes on deserialized properties and arrays so it's possible to perform decoded instanceof OriginalClass checks.

How to install

yarn add @elderapo/protobuf-lite @abraham/reflection
# or
npm install @elderapo/protobuf-lite @abraham/reflection

If you are already using reflect-metadata package or want to use it instead of @abraham/reflection go ahead. I decided to use @abraham/reflection because its bundle is much smaller.

Usage

import "@abraham/reflection";
import { decode, encode, ProtobufLiteProperty } from "@elderapo/protobuf-lite";

class Person {
  @ProtobufLiteProperty()
  public firstName: string;

  @ProtobufLiteProperty()
  public secondName: string;

  @ProtobufLiteProperty({ optional: true })
  public nickname?: string;

  @ProtobufLiteProperty()
  public isProgrammer: boolean;

  @ProtobufLiteProperty()
  public birthDate: Date;

  @ProtobufLiteProperty({ type: () => String })
  public hobbies: string[];
}

const payload: Person = {
  firstName: "Joe",
  secondName: "Doe",
  isProgrammer: true,
  hobbies: ["swimming", "eating"],
  birthDate: new Date("1990")
};

const encoded = encode(Person, payload);
const decoded = decode(Person, encoded);

expect(Buffer.isBuffer(encoded)).toBe(true);
expect(decoded).toBeInstanceOf(Person);

expect(decoded.firstName).toBe("Joe");
expect(decoded.secondName).toBe("Doe");
expect(decoded.isProgrammer).toBe(true);

expect(decoded.hobbies).toBeInstanceOf(Array);
expect(decoded.hobbies).toMatchObject(["swimming", "eating"]);

expect(decoded.birthDate).toBeInstanceOf(Date);
expect(decoded.birthDate.getTime()).toBe(new Date("1990").getTime());

console.log(`Everything is working as expected 👍`);

Todo

  1. add possibility to manually specify protobuf types (bool, uint32 etc..)
  2. figure out if it's possible to automatically generate *.proto files from fields metadata

License

FOSSA Status

About

Minimalistic, strongly typed typescrpt library for protobufers

Topics

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •