Unknown error occurred in Eventstore: Unable to identify the BadRequest issue

I'm encountering an error while using Eventstore, specifically: Could not recognize BadRequest;

The error message is originating from:

game process tick failed UnknownError: Could not recognize BadRequest
    at unpackToCommandError (\node_modules\@eventstore\db-client\dist\streams\appendToStream\unpackError.js:53:12)
    at ClientDuplexStreamImpl.<anonymous> (\node_modules\@eventstore\db-client\dist\streams\appendToStream\batchAppend.js:38:66)

It appears that the issue lies within my handler function:

async function   gameProcessPush(channel,event) {
    console.log("pushing:",event);
    try {
        console.log("trying to append..:",event);

           await client.appendToStream("factory",[event]);
           console.log("appending to stream");
        } catch(e) {
            console.log("game process tick failed",e);
            throw  {live: false, code: 26, event: event}
        }
        console.log("game processing...");

}

Can anyone help me identify what I might be doing incorrectly here?

Here's the remaining debug code:

processing factory failed {
  live: false,
  code: 26,
  event: { type: 'factory-creation', sub: 'sub-factory', userid: 1 }
}
result in :  undefined

Below is the full code snippet for reference:

import { streamNameFilter } from "@eventstore/db-client";
import { createSecureServer } from "http2";
import { runMain } from "module";
import { eventNames, mainModule } from "process";
import { arrayBuffer } from "stream/consumers";
import { SubscriptionInfo } from "./generated/persistent_pb";
import { AllStreamPosition } from "./generated/shared_pb";

const {EventStoreDBClient, FORWARDS, StreamNotFoundError, jsonEvent, START, END, excludeSystemEvents, eventTypeFilter} = require("@eventstore/db-client");

  
  const client = new EventStoreDBClient({
    endpoint: "localhost:2113",
}, {
    insecure: true,
});

    interface creationFactory {
        userid: string,
        location: [number,number,number],
        name: string
        type: string,
    }

class Factory {


    public async create(creation : creationFactory) {
        console.log("creating new factory.....",creation);   
        const NewFactoryEvent = CreateEvent("factory-creation",{userid: 1, sub: "sub-factory"})
        try {
            console.log("creating newfac",NewFactoryEvent);
            await gameProcessPush("factory",NewFactoryEvent)
        } catch(error) {
            console.log("processing factory failed",error);
        }
    }


}

function CreateEvent(type,data) {
    return  {type: type, sub: data.sub,
        userid: data.userid,
        
    }
}

async function   gameProcessPush(channel,event) {
    console.log("pushing:",event);
    try {
        console.log("trying to append..:",event);

           await client.appendToStream("factory",[event]);
           console.log("appending to stream");
        } catch(e) {
            console.log("game process tick failed",e);
            throw  {live: false, code: 26, event: event}
        }
        console.log("game processing...");

}


//new Factory().create({userid: "1", location: [1,1,1], name: "test bank", type: "BANK"});
async function test() {
    try {
       await  new Factory().create({
            userid: "1",
            location: [0,0,0],
            name: "test",
            type: "factory",
        });
          
    } catch(e) {
        console.log("factory creation faileD");
    }
}

test().catch((e) => {console.log("test failed",e)}).then(function (data) {
console.log("result in : ",data);
});

Answer №1

Overview

Data Requirements

In an EventStore system, an event must adhere to a specific structure known as the EventData object. This object contains two essential properties:

  • type: A string indicating the type of the event.
  • data: The payload, represented as a byte array, typically in JSON format.

Instructions for Appending Events

To append events in EventStore, use the appendToStream method as shown below:

await client.appendToStream(STREAM_NAME, event);

Additional Resources

  • Guide to Creating an Event
  • Appending Events Tutorial

Identified Issues

Your code exhibits two potential problems:

  1. You are attempting to append an Array instead of an actual EventData object ([event]).
  2. The structure of your event does not align with that of an EventData object, evident from your debug log and the CreateEvent function.

Suggested Solution

To address these issues, process your input event to construct a valid EventData object before appending it:

async function gameProcessPush(channel, event) {
  try {
    const eventData = jsonEvent({
      type: event.type,
      data: {
        sub: event.sub,
        userid: event.userid,
      },
    });
    await client.appendToStream("factory", eventData);
  } catch (e) {
    throw { live: false, code: 26, event: event };
  }
}

Answer №2

If you haven't already, make sure to check out the information provided in the documentation for EventStore.

If you need to review something, you can visit this link -

Try modifying [event] to event

async function   gameProcessPush(channel,event) {
    console.log("pushing:",event);
    try {
        console.log("trying to append..:",event);

           await client.appendToStream("factory",event);
           console.log("appending to stream");
        } catch(e) {
            console.log("game process tick failed",e);
            throw  {live: false, code: 26, event: event}
        }
        console.log("game processing...");

}

Give it a try and see if it works as expected

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

Using jQuery to find duplicated records within two JSON object arrays

Here is the structure of my first Json Array: [ {"Invent":"4","Beze":"256","mail":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f7f4f5d6f7f4f5b8f5f9fb">[email protected]</a>"}, {"Invent":"4","Beze":"2 ...

Substitute the division

Can I make the old div change its position and move to the side when I add a new div? And can all the old divs be hidden when adding four new divs? This is for my full news website and I want this applied to all four pages. First page: https://i.sstatic. ...

Transforming class attributes in Typescript

I am facing a situation where I need to alter the type of a variable that stores an object based on certain conditions. Here is the variable in question: class MyClass { public referrers: SelectItemGroup[]; } The issue arises when I only need to add a ...

The Next.js middleware, specifically NextRequest.nextUrl.locale, will return an empty string once it is deployed

Encountering a bug in the next-js middleware The middleware function is returning a NextRequest param According to the documentation from Next.js: The NextRequest object is an extension of the native Request interface, with the following added metho ...

Troubles arise when attempting to utilize yarn for my projects

Whenever I enter the command yarn start in the terminal, I get this output: yarn run v1.22.4 $ react-scripts start 'react-scripts' is not recognized as an internal or external command, operable program or batch file. error Command fai ...

Yii2 pjax not refreshing properly when updating records in the gridview

I have successfully implemented functionality in my grid-view to control the number of rows displayed per page. This feature includes a drop-down menu with options such as 5, 10, 25, 50, and 100 rows. Whenever a user selects an option from the drop-down, I ...

Accessing JSON data from a URL in AngularJS

Just dove into the world of fetching and displaying JSON data in my AngularJS app for the first time, but unfortunately, no data is showing up. Here's the code I have implemented: HTML <div ng-app="myApp" ng-controller="custom ...

AngularJS is patiently waiting for the tag to be loaded into the DOM

I am trying to incorporate a Google chart using an Angular directive on a webpage and I want to add an attribute to the element that is created after it has loaded. What is the most effective way to ensure that the element exists before adding the attribut ...

Avoiding the need to wait for completion of the jQuery $.get function

Currently, I am executing a basic jQuery GET request as shown below and it is functioning correctly. $.get("http://test.example.com/do-something", function (data) { console.log("test work done"); }); The GET request is initiated without affecting the ...

What is the method for accessing the locale and messages of the IntlProvider within a component?

My index.js file includes the following code: import trFi from './translations/fi_FI.json'; import trSv from './translations/sv_SE.json'; ReactDOM.render( <IntlProvider locale={my_locale} messages={{ fi: trFi, sv: trSv } ...

Error in Express.js application: form fields lose their values

I am currently developing a blogging application using Express, EJS and MongoDB. One of the main features is an "Add New Post" form with an addPost() method in the controller; exports.addPost = (req, res, next) => { const errors = validationResult ...

Choosing HTML elements within nested DIV tags

In the process of creating a Hangman-style game using javascript/jQuery, I encountered an issue with selecting HTML content from virtual keyboard keys : <div class="square keyboard"> <div class="content"> <div class="table"> ...

To retrieve a CSV file on the frontend, simply click a button in an AngularJS application that communicates with NodeJS and ExpressJS

How can I download a .csv file from the frontend? This is the code I am currently using: $http.get('/entity/consultations/_/registerationReport' ) .success(function (data) { myWindow = window.open('../entity/consultations/_/r ...

Duplicate the identical data retrieval query, this time utilizing a JavaScript Ajax post method

To enhance the data request query, implement a JavaScript Ajax post method to avoid page refresh when the button is pressed. This will allow for requesting another page and displaying it in a designated section on the webpage. Here's the code snippet ...

HTML Canvas resizing challenge

My goal is to resize the canvas to fit inside its parent div within a Bootstrap grid, but I'm running into an issue where the canvas keeps expanding to 2000px x 2000px. Despite successfully resizing based on console.log outputs showing the same dimens ...

Unable to insert an array within a function

I've searched for the answer but couldn't find it - my array is not pushing to datahasil. How can I push the array hasil into datahasil...?? const data1 = await JadwalBooking.aggregate([{ $project: { "keterangan": "$keterangan", ...

How can I extract the value of a JavaScript variable using jsoup in an HTML document?

<html> <script type="text/javascript"> var map = null; jQuery(function($) { L.marker([50.065407, 19.945104], {title: 'Cat'}) .bindPopup('<h3>Cat</h3> ...

Deactivate the Autofill feature on Google Toolbar

Dealing with the Google Toolbar's autofill feature has been a constant frustration in my web development journey over the years. I have resorted to creating a timer control to monitor changes, as the developers overlooked firing change events on contr ...

Display or conceal nested divs within ng-repeat loop

I set up a div with sub divs to establish a nested grid system. There are three levels altogether: MainDiv - Always Visible SecondDiv - Display or conceal when MainDiv is clicked on ThirdDiv - Display or conceal when SecondDiv is clicked on <div c ...

Encountering issues with running an AngularJS application (version 1.6) in Visual Studio following the activation of script

I am new to working on an angular 1.6 application and still learning the ropes. The project consists of an asp.net web api project that needs to be run before starting the angular project. Everything was running smoothly until I tried to debug a parameter ...