@elderapo/protobuf-lite
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
- [ ] add possibility to manually specify protobuf types (bool, uint32 etc..)
- [ ] figure out if it's possible to automatically generate
*.proto
files from fields metadata