Getting started (TypeScript)
Getting Started with Bebop in TypeScript
Bebop is a high-performance serialization framework designed for efficient data transfer. This guide will walk you through setting up Bebop in your TypeScript project, creating schemas, and using the generated code.
Installation
First, let’s install the necessary packages:
| Package | Downloads |
|---|---|
| bebop | |
| bebop-tools |
Install Bebop Runtime
npm add bebopyarn add bebopInstall Bebop Compiler
npm add bebop-toolsyarn add bebop-toolsProject Initialization
Initialize your Bebop project:
npx bebopc --inityarn bebopc --initThis command creates a bebop.json file in your project root. Open this file and add a TypeScript generator:
{ "include": [ "**/*.bop" ], "generators": { "ts": { "outFile": "src/bops.gen.ts" } }}This configuration tells Bebop to:
- Include all
.bopfiles in your project - Generate TypeScript code
- Output the generated code to
src/bops.gen.ts
Creating Bebop Schemas
Bebop uses its own schema language to define data structures. Create a new file with a .bop extension (e.g., schemas.bop) and define your schemas:
struct Person { string name; uint32 age;}
struct Team { string name; Person[] members;}Generating TypeScript Code
After defining your schemas, generate the TypeScript code:
npx bebopc buildyarn bebopc buildThis command will generate TypeScript code based on your Bebop schemas.
Using Generated Code
Now you can use the generated code in your TypeScript project. Here’s an example of how to create and encode a Person object:
import { Person } from './src/bops.gen';
const person = new Person({ name: "Spike Spiegel", age: 27});
// Encode the person object to a Uint8Arrayconst encoded = person.encode();
// Decode the Uint8Array back to a Person objectconst decoded = Person.decode(encoded);
console.log(decoded.name); // Output: Spike Spiegelconsole.log(decoded.age); // Output: 27JSON Serialization (JSON-Over-Bebop)
Bebop supports JSON serialization using JSON-Over-Bebop. This format allows for efficient serialization and deserialization of Bebop objects to and from JSON.
For more information on JSON-Over-Bebop, refer to the JSON-Over-Bebop specification.
Here’s how to use JSON serialization:
// Serialize to JSON-Over-Bebopconst jsonString = person.stringify();
// Deserialize from JSON-Over-Bebopconst fromJson = Person.fromJSON(jsonString);