Skip to content

Encoding and decoding of JavaScript objects to and from binary based around pre-existing Zod schemas

License

Notifications You must be signed in to change notification settings

KennanHunter/zod-binary-interface

Repository files navigation

NOTE: This project is still very much in Alpha. Most stuff doesn't work and what does may change at any moment

Zod Binary Interface

GitHub Workflow Status Lines of code npm NPM Code coverage

Zod Binary Interface is a FOSS library that allows for the encoding and decoding of JavaScript and Typescript objects to and from binary. It accomplishes this by utilizing the often pre-existing Zod schema definitions.

Usage

Installing

# npm
npm install zod-binary-interface
# Yarn
yarn add zod-binary-interface

Global Instance

The entire library is interacted with through a global instance of ZodBinaryInterface, which stores and flattens the zod schema all data goes through.

import { z } from "zod";
import { ZodBinaryInterface } from "zod-binary-interface";

const exampleSchema = z.schema({
  foo: z.string(),
  bar: z.number(),
});

const zbi = ZodBinaryInterface.fromSchema(exampleSchema);

Encoding

Encoding transforms your data from a JavaScript object to a binary ArrayBuffer.

Binary ArrayBuffers like these can be easily transferred in requests and saved to local files.

const sampleData: z.infer<typeof exampleSchema> = {
  foo: "Foo",
  bar: 100,
};

const buffer = zbi.encode(sampleData);
//    ^?: ArrayBuffer

Decoding

Decoding transforms your data from a Javascript ArrayBuffer, back into the original object form.

Decoding internally utilizes the supplied zod schema to validate the data.

const data = zbi.decode(buffer);
//    ^?: { foo: string, bar: number }

Benchmarks

Benchmarking is an ongoing process.

Name Iterations ZBI Time ZBI Size JSON Time JSON Size
Booleans 1 1.699104 seconds 4 bytes 0.046286 seconds 455 bytes
Booleans 100 0.137128 seconds 4 bytes 0.008153 seconds 455 bytes

Developing

git clone https://github.com/KennanHunter/zod-binary-interface.git
cd zod-binary-interface

yarn
yarn test

# Benchmarking (builds in background)
yarn benchmark

# Only needed for final publishing
yarn build

There exists recommended extensions and basic settings in the .vscode folder.

About

Encoding and decoding of JavaScript objects to and from binary based around pre-existing Zod schemas

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

Languages