Protobuf.js: The Writer is not completing the operation

I have recently come across an unusual issue while incorporating Protobuf into my TypeScript frontend. My approach involves using Axios to communicate with my REST API and leveraging the protobuf.js library for handling Protobuf in the frontend. Since I am relatively new to working with Protobuf, I suspect that my lack of familiarity might be causing the problem.

The complication arises when I attempt to make multiple calls to the API with a specific payload.

For instance, let's say I intend to post three objects: object_1, object_2, and object_3. As a result, I end up making three separate post requests. The initial request consistently processes correctly—object_1 successfully gets added to the backend. However, subsequent posts for object_2 and object_3 seem to retransmit object_1 instead. Upon examining this issue further, I discovered that my protobuf is getting appended to the existing payload. This results in the second request containing object_1 and

object_2</code}, while the third one includes <code>object_1
, object_2, and object_3. Consequently, the API only interprets the first protobuf (i.e., object_1) and ends up adding object_1 three times.

In accordance with the documentation, here is how I am utilizing the protobuf.js package:

const message = Message.create({ message: 'hello' });
const buffer = Message.encode(message).finish();
await axios.post([...] message [...]);

Has anyone else faced a similar issue? Where could I possibly be going wrong?

Thank you!

Answer №1

When using the Writer object in protobufjs, a shared array buffer is utilized.

However, when making an axios post request, the byteOffset and byteLength properties are not considered, resulting in the entire shared buffer being used instead of just the desired bytes.

To extract only the relevant bytes, you can use the following code:

const message = Message.create({ message: 'hello' });
const x = Message.encode(message).finish();
const buffer = new Uint8Array(x.buffer, x.byteOffset, x.byteLength);

In my view, protobufjs may be a bit outdated. As the author of protobuf-ts, I openly recommend checking out protobuf-ts if you are unsatisfied with protobufjs. With protobuf-ts, encoding your message to binary would look like this:

const message = Message.create({ message: 'hello' });
const bytes: Uint8Array = Message.toBinary(message);

Furthermore, it also offers support for Angular through auto-generated Twirp clients.

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

Ways to relay messages from `Outlet` to web pages

My Layout.tsx: import { FC, useState } from 'react'; import * as React from 'react'; import { Outlet } from 'react-router-dom'; export const Layout: FC = () => { const [username, setUsername] = useState('John') ...

Encountering a situation where d3.events is returning null within Angular 2 TypeScript code

Seeking to enhance my d3 maps with tooltips, I came across a helpful code snippet at this link However, upon implementing the same code in an Angular 2 TypeScript file, an error emerged: Error: Cannot read property 'transition' of undefined Th ...

Issue with Typescript flow analysis when using a dictionary of functions with type dependency on the key

I am utilizing TypeScript version 4.6 Within my project, there exists a type named FooterFormElement, which contains a discriminant property labeled as type type FooterFormElement = {type:"number",...}|{type:"button",...}; To create instances of these el ...

Is the Angular Karma test failing to update the class properties with the method?

I am struggling to comprehend why my test is not passing. Snapshot of the Class: export class Viewer implements OnChanges { // ... selectedTimePeriod: number; timePeriods = [20, 30, 40]; constructor( /* ... */) { this.selectLa ...

How can we enhance intellisense to recognize instance members of an interface when using dynamic indices?

In the midst of developing an angular project, I am currently utilizing an interface to specify a configuration for a module. The design of the interface revolves around mapping names to objects and is relatively straightforward: export interface NamedRou ...

The error message "Can't resolve all parameters for CustomerService" is preventing Angular from injecting HttpClient

I have a customerService where I am attempting to inject httpClient. The error occurs on the line where I commented //error happens on this line. Everything works fine until I try to inject httpClient into my service. The error message is: `compiler.js: ...

Creating Dynamic ion-card Elements in Typescript by Programmatically Changing Values

Currently, I am working on a basic app that retrieves posts from the server and displays them as cards on the screen. At this early stage, one of my main challenges is figuring out how to dynamically add ion-card elements with changing content and headers ...

Is it possible for me to create an If statement that can verify the current index within a Map?

I have the following TypeScript code snippet: export default class SingleNews extends React.Component<INews, {}> { public render(): React.ReactElement<INews> { return ( <> {this.props.featured ...

"Discovering the secrets of incorporating a spinner into Angular2 and mastering the art of concealing spinners in Angular

When experiencing delay in image loading time, I need to display a spinner until the image loads completely. What is the best way to achieve this on the Angular 2 platform? <div id='panId' class="container-fluid" > This section ...

Tips for patiently waiting for a method to be executed

I have encountered a situation where I need to ensure that the result of two methods is awaited before proceeding with the rest of the code execution. I attempted to use the async keyword before the function name and await before the GetNavigationData() me ...

Nuxt - It is not possible to use useContext() within a watch() callback

I'm currently utilizing version 0.33.1 of @nuxtjs/composition-api along with Nuxt 2. Here's a snippet from my component: import { defineComponent, useContext, useRoute, watch } from '@nuxtjs/composition-api'; export default defineCompo ...

How to dynamically modify ion-list elements with Ionic on button click

Imagine having 3 different lists: List 1: bus, plane List 2: [related to bus] slow, can't fly List 3: [related to plane] fast, can fly In my Ionic Angular project, I have successfully implemented the first ion-list. How can I dynamically change th ...

NodeJS Jest test failing due to a global variable being set for a different test already

I am currently working on a project in TypeScript using Node.js and Jest. I have a function that may or may not modify a global variable, which is a TypeScript Map. After one test modifies the global variable, it retains that value for subsequent tests. I ...

unable to retrieve the values of the rowdata in GridOption

ngOnInit(): void { this.fetchAllAnimeReviews(); } public fetchAllAnimeReviews(){ this.animeservice.getAllAnimeReviews() .subscribe( response => { this.Anime = response; this.gridOption = this.createGridO ...

Update the TemplateUrl according to the URL Parameters (GET)

I've created a basic Angular code snippet (test.component.ts) that retrieves a variable from GET parameters: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ select ...

Determining the return type based on an optional generic type in TypeScript

I have created a function that generates an object (map) [key] : value from an array. My goal is to make the value method optional, and if not provided, simply return the item as it is. Here is the code I have written: export default class ArrayUtil ...

Issue with React Redux: Store dispatch not causing component update

I have recently implemented React Redux in my project, but I seem to be encountering some issues. Despite changing the state, the value remains the same. I attempted to use useStore(), but it does not take any parameters. Can anyone provide insight into wh ...

Is there a tool in Node.js to set up a new project, similar to the scaffolding feature in Visual Studio for C# projects

Is there a way to efficiently create a node.js project with TypeScript and Express, and embed an SPA client using React and Redux templates written in TypeScript as well? Is there a scaffolding tool available to streamline this process, similar to the ea ...

Utilizing Provide/Inject in Vue 3 Typescript to retrieve a method within a component, encountering the possibility of an 'undefined' Error Object

Having trouble calling the loginWithRedirect function within the header.vue component using inject feature in Vue 3 and Typescript. ERROR in src/components/global/HeaderMenu.vue:77:17 TS2339: Property 'loginWithRedirect' does not exist on type ...

TypeScript type that accommodates all object interfaces

I have several functions that all take the same type as input but return different types of interfaces. I'd like to define a type that can encompass all these functions, but when I try to do so with: const f: (arg: number) => Object = func; I enc ...