How can we design a Protobuf structure for a map that contains an array of objects as the value?

I need help with encoding a map in a protobuf format. Here is an example of the map:

const newVisMap = new Map<number, IOutput[]>();

The map contains an array of objects that share a common interface, as shown below (with one optional property):

interface IOutput {
    glyph: string,
    color: string,
    hex?: string,
    order: number
}

I am wondering how to properly encode this map as a field within a protobuf message or if I should convert it to another format. I am using the protobuf.js npm module for this task.

Answer №1

The question lacks important details, but it seems that the objects sharing the same interface are actually of different types based on clues like 'glyph' and 'hex' being strings.

The issue here lies in the fact that Protocol Buffers (GPB) thrives on strong typing; it is most effective when the schema provides a complete definition of the data. Using strings implies that the data will need to be parsed in some way, rather than clearly defined by the schema.

For instance, representing color as a string could be improved by using three integers for red, green, and blue values instead. A color name can be ambiguous! Is it a hex value or something else?

If the information in 'glyph' alone isn't sufficient to create an object, you risk separating vital details between the code and schema. While this may work for your own use, it could pose challenges if the data needs to be interpreted by a system written in a different language – they won't have access to your constructors!

A better approach would be to define each possible object thoroughly in GPB messages within a schema, then encapsulate them in an overarching 'oneof' message when sending. This ensures clarity on the object type and provides explicit data about it.

If the objects share similar content and behavior, creating a universal class to describe them all might suffice.

Your suggestion about serializing the map and transmitting it raises the importance of serialization methods; either enhance the GPB schema to accommodate this process or consider alternatives.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What causes TypeScript 3.7.5 to trigger an error while typing a function that accepts an array as a parameter?

I'm facing a perplexing compiler error while trying to define a function that requires an array as its sole argument. Below is a concise scenario to reproduce the issue: http://www.example.com import React from 'react' type FooProps = { ...

Ways to RESOLVE implicit any for accessing array property

Check out the code snippet below: function getUsername(): string { return 'john_doe'; } function sampleFunction(): void { const data = {}; const username: string = getUsername(); const age: any = 30; data[username] = age; // ...

Turf.js - Missing type declarations when importing into a Vue/Vite environment

Struggling with Turf.js's bbox functionality. Despite all my efforts, TypeScript type definitions remain elusive. I attempted the following steps: Included in package.json: "dependencies": { ... "@turf/turf": "6.5.0&q ...

[Vue warning]: The property "text" was accessed during rendering, however it is not defined on the current instance using Pug

Looking for some guidance from the Vue experts out there. I've recently started working with Vue and I'm attempting to create a view that verifies an email with a unique code after a user signs up. Right now, my view is set up but it's not c ...

Why isn't the parent (click) event triggered by the child element in Angular 4?

One of my challenges involves implementing a dropdown function that should be activated with a click on this specific div <div (click)="toggleDropdown($event)" data-id="userDropdown"> Username <i class="mdi mdi-chevron-down"></i> </d ...

Unable to swap out string with text box in TypeScript

I am trying to swap __ with a text box in Angular 2/4. Take a look at the example provided in the link below. https://stackblitz.com/edit/angular-ajkvyq?file=app%2Fapp.component.ts ...

Question from Student: Can a single function be created to manage all text fields, regardless of the number of fields present?

In my SPFX project using React, TypeScript, and Office UI Fabric, I've noticed that I'm creating separate functions for each text field in a form. Is there a way to create a single function that can handle multiple similar fields, but still maint ...

Is the return type determined by the parameter type?

I need to create an interface that can handle different types of parameters from a third-party library, which will determine the return type. The return types could also be complex types or basic types like void or null. Here is a simple example demonstra ...

Are union types strictly enforced?

Is it expected for this to not work as intended? class Animal { } class Person { } type MyUnion = Number | Person; var list: Array<MyUnion> = [ "aaa", 2, new Animal() ]; // Is this supposed to fail? var x: MyUnion = "jjj"; // Should this actually ...

Is there a way to verify if the database has been successfully saved and the API call has been

I am currently in the process of developing a function that calls two other functions. Function 1 is responsible for saving an object to a database, while function 2 performs an API call. async createMSCalendarEntry(start: Date, end: Date, name: string ...

Issue encountered when importing a font in TypeScript due to an error in the link tag's crossorigin

How do I troubleshoot a TypeScript error when importing a custom font, such as a Google font? <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> Below is the specific error message: Type 'boolean' is ...

Getting the PlayerId after a user subscribes in OneSignal with Ionic2

Currently working on an app with Ionic2 and facing a challenge with retrieving the player id after a user subscribes in order to store it in my database. Any suggestions on how I can retrieve the unique player id of OneSignal users post-subscription? ...

Unit testing the error function within the subscribe method in Angular

I've been working on a unit test for the subscribe call, but I'm struggling to cover the error handling aspect of the subscribe method. The handleError function deals with statusCode=403 errors and other status codes. Any assistance would be grea ...

cssclassName={ validatorState === RIGHT ? 'valid' : 'invalid' }

Is there a way to dynamically add different classes based on validation outcomes in React? My current implementation looks like this: className={ validatorState === RIGHT ? 'ok' : 'no' } However, I also need to handle cases where the ...

The Art of Dynamic Component Manipulation in Angular

The current official documentation only demonstrates how to dynamically alter components within an <ng-template> tag. https://angular.io/guide/dynamic-component-loader My goal is to have 3 components: header, section, and footer with the following s ...

What is the best way to broaden the capabilities of function objects through the use of

Below is a code snippet that raises the question of how one should define certain types. In this scenario, it is required that Bar extends Foo and the return type of FooBar should be 'a'. interface Foo { (...args: any):any b: string } i ...

React function failing to utilize the latest state

I'm facing an issue with my handleKeyUp function where it doesn't seem to recognize the updated state value for playingTrackInd. Even though I update the state using setPlayingTrackInd, the function always reads playingTrackInd as -1. It's p ...

When trying to upload a file with ng-upload in Angular, the error 'TypeError: Cannot read properties of undefined (reading 'memes')' is encountered

Struggling with an issue for quite some time now. Attempting to upload an image using ng-upload in angular, successfully saving the file in the database, but encountering a 'Cannot read properties of undefined' error once the upload queue is comp ...

Is it possible for me to listen to an AngularJS event using regular JavaScript, outside of the Angular framework?

Is it possible to listen to an event triggered in AngularJS using regular JS (outside of Angular)? I have a scenario where an event is being emitted using RxJS in Angular 2. Can I observe that event from pure JS? Here's some example pseudo code: imp ...

Looking for a solution to the error message: "X is not able to be assigned to the type 'IntrinsicAttributes & Props'"

Greetings everyone! I need some assistance in setting up single sign-on authentication using React, Azure AD, and TypeScript. I'm encountering a type error in my render file and I'm unsure of how to resolve it. Below is the specific error message ...