0.0.2 • Published 2 years ago

@bpinternal/ptb-schema v0.0.2

Weekly downloads
-
License
AGPL-3.0
Repository
-
Last release
2 years ago

Protobuf Schema

Small wrapper above protobufjs that allows infering a TypeScript type directly from a protobuf schema in a zod-like fashion.

Defining a PTBMessage allows both to decode/encode data structures and to define types.

Usage

import * as ptb from '@bpinternal/ptb-schema'

let userid = 0
const PtbUser = new ptb.PTBMessage('User', {
  email: { id: userid++, rule: 'required', type: 'string' },
  firstName: { id: userid++, rule: 'optional', type: 'string' },
  lastName: { id: userid++, rule: 'optional', type: 'string' },
  birthDate: { id: userid++, rule: 'required', type: 'int32' },
  isStrong: { id: userid++, rule: 'required', type: 'bool' },
  favoriteFood: { id: userid++, rule: 'repeated', type: 'string' }
})

let partyid = 0
const PtbParty = new ptb.PTBMessage('Party', {
  users: { id: partyid++, rule: 'repeated', type: PtbUser }
})

type User = ptb.Infer<typeof PtbUser>
type Party = ptb.Infer<typeof PtbUser>

const eminemBenchPress = 145
const strongThreshold = 225

const eminem: User = {
  email: 'slim.shady@botpress.com',
  firstName: 'eminem',
  lastName: undefined,
  birthDate: Date.now(),
  favoriteFood: ["mom's spaghetthi"],
  isStrong: eminemBenchPress >= strongThreshold
}

const encoded: Uint8Array = PtbParty.encode({
  users: [eminem]
})

console.log('bytes:', encoded.length)

const decoded = PtbParty.decode(encoded)
console.log('decoded:', decoded)

Disclaimer ⚠️

This package is published under the @bpinternal organization. All packages of this organization are meant to be used by the Botpress team internally and are not meant for our community. However, these packages were still left intentionally public for an important reason : We Love Open-Source. Therefore, if you wish to install this package feel absolutly free to do it. We strongly recomand that you tag your versions properly.

The Botpress Engineering team.

Licensing

This software is protected by the same license as the main Botpress repository. You can find the license file here.