1.3.1 • Published 5 years ago

@elderapo/protobuf-lite v1.3.1

Weekly downloads
-
License
MIT
Repository
github
Last release
5 years ago

@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 👍`);

Check out tests cases for more examples!

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

1.3.1

5 years ago

1.3.0

5 years ago

1.2.0

5 years ago

1.1.3

5 years ago

1.1.2

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago