near / borsh-js

TypeScript/JavaScript implementation of Binary Object Representation Serializer for Hashing
Apache License 2.0
112 stars 38 forks source link

How to serialize or create schema for vec of structs #55

Closed postnetsol closed 10 months ago

postnetsol commented 2 years ago

in rust

#[derive(Debug, BorshDeserialize, BorshSerialize)]
pub struct ContentStorage {
    pub posts: Vec<Post>
}

#[derive(Debug, BorshDeserialize, BorshSerialize)]
pub struct Post {
    pub post_id: String,            // unique string
    pub image_url: Option<String>,  // ipfs link
    pub text: Option<String>,       // text for curr post
    pub owner: [u8; 32],            // post's owner
    pub likes_count: u32,           // likes of current post
    pub repost_count: u32,          // reposts
    pub comments: Vec<String>      // list of comments
}

in ts

export class ContentStorage {
    posts: Post[]
    static schema: Schema = new Map([
        [ContentStorage,
            {
                kind: 'struct',
                fields: [
                    ['posts', ['structs']],
                ]
            }],
    ]);

    constructor(posts: Post[]) {
        this.posts = posts
    }

    serialize(): Uint8Array {
        return serialize(ContentStorage.schema, this);
    }

    deserialize(data: Buffer): ContentStorage {
        return deserialize(ContentStorage.schema, ContentStorage, data);
    }
}

when I try to run it my result: TypeError: writer[capitalizeFirstLetter(...)] is not a function

marcus-pousette commented 1 year ago

I have created a Typescript implementation of borsh spec. @dao-xyz/borsh that makes this kind of schema a lot easier to define in Typescript. If you want to stick with this lib I would suggest you to read the unit-test to see if you find anything that could help you