Incorporating observables into an existing axios post request

Currently, I have an API using axios to send HTTP POST requests. These requests contain logs that are stored in a file. The entire log is sent at once when a user signs into the system.

Now, I've been instructed to modify the code by incorporating RxJS and sending the file contents (logs) in streams every x minutes...

If you have any idea on how to tackle this issue or know of any helpful resources, your input would be greatly appreciated!

async deliverData(UserName: string, Log: string[]): Promise<UserInfo>{
  return this.apiService.post({
    baseUrl: Something.SomethingUrl,
    endpoint: "/post/log"
    timeout: 15000
    headers:{      }
   },
    {
      userName: userName,
      Log: Log[0]
     }

Answer №1

Consider using axios-observable instead of axios for managing subscriptions. Using subscriptions over promises allows for easier unsubscription, which is a big advantage. To implement this, you can place your log sending request subscription within a BehaviorSubject (import { BehaviorSubject } from 'rxjs';) and schedule the call to the behavior subject on a timer. Here's an example:

export default class PollValue<T> {
    date: Date;
    value: T;

    constructor(value: T) {
        this.date = new Date();
        this.value = value;
    }

    // Ensures a minimum amount of time has elapsed
    getTimeout(minTimeMS: number) {
        const timeElapsed = new Date().getTime() - this.date.getTime();
        return timeElapsed < minTimeMS ? minTimeMS - timeElapsed : 0;
    }
}

// using true or false to indicate whether we sent logs the last time or not
const sendLogs = new BehaviorSubject(new PollValue<boolean>(false));
sendLogs.subscribe(lastValue => {
    setTimeout(() => {
        if (thereAreLogsToSend) {
            // sendLogs is a function containing your axios-observable instance and request 
            this.yourLogService.sendLogs(<pass logs here>).subscribe(result => {
                sendLogs.next(new PollValue(true));
            });
        } else {
            sendLogs.next(new PollValue(false));
        }
         
    }, lastValue.getTimeout(900000)); // ensure at least 15 mins have elapsed before sending again

    if (someStopSendingCondition) {
        sendLogs.unsubscribe();
    }
});

If you're looking to send your request as a stream, you may find examples here helpful. I don't have much experience working with streams in REST architecture, so I may not be the best resource for that specific topic.

I hope this information proves useful, even though my response may be delayed...

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

Display various react components based on the value of the property

I am in the process of creating an input component in ReactJs with typescript. The input can vary in types such as text, date, select, or textarea. Depending on the type provided, the displayed control will differ. For example, if set to text, <input t ...

Dealing with throwing Exceptions in jest: A guide for developers

I have developed a method that throws an exception when the provided password does not match a regex pattern. I attempted to handle this in Jest. it('Should prevent insertion of a new user if the password doesn't match the regex', async () ...

sticky header on pinned tables in a React data grid

I have combined 3 tables together, with the middle table containing a minimum of 15 columns. This setup allows users to horizontally scroll through the additional columns conveniently. However, I am facing a challenge in implementing a sticky header featu ...

How can one effectively monitor the progress of multiple ajax requests in Angular8 for optimal professionalism?

There is a single completed variable made up of 6 parts, outlined below: selectedCandidateData: Candidate = { candidateBasic: null, experienceList: null, educationList: null, certificationList: null, candidateAbout: null, }; Each part ...

Understanding how to efficiently map through FontAwesome icons using React TypeScript and effectively showcase them on the frontend

I am in the process of developing a versatile component that allows me to input the href, target, and rel attributes, along with specifying the FontAwesome Icon I want to utilize. My goal is to be able to pass multiple icons into this list, which will then ...

Arrange the array based on the order of the enumeration rather than its values

Looking to create an Array of objects with enum properties. export enum MyEnum { FIXTERM1W = 'FIXTERM_1W', FIXTERM2W = 'FIXTERM_2W', FIXTERM1M = 'FIXTERM_1M', FIXTERM2M = 'FIXTERM_2M', FIXTERM3M = 'FIX ...

Utilizing the React TypeScript useContext hook with useReducer for state management

I'm struggling to identify the type error present in this code snippet import React from 'react'; interface IMenu { items: { title: string, active: boolean, label: string }[] } type Action = | { type: 'SET_ACTIVE&a ...

Utilizing AJAX to Send a POST Request to the Google Chart API

Hello everyone, I have been attempting to utilize the Google Chart API to create some charts on a website using AJAX to avoid page reloading. However, I am encountering an issue. I need to make POST requests but I am unsure if AJAX supports this. Here is ...

Ways to incorporate forms.value .dirty into an if statement for an Angular reactive form

I'm a beginner with Angular and I'm working with reactive Angular forms. In my form, I have two password fields and I want to ensure that only one password is updated at a time. If someone tries to edit both Password1 and Password2 input fields s ...

Ensuring the Presence of a Legitimate Instance in NestJS

I have been working on validating my request with the Product entity DTO. Everything seems to be in order, except for the 'From' and 'To' fields. The validation works correctly for the Customer and Type fields, but when incorrect data i ...

Formulate a multi-line string using a collection in React's JavaScript framework

I'm working on a React function that involves a set and I need to update an HTML element using the data from this set. Below is an example of my code: const updateElement = (mySet) => { document.getElementById('myId').innerHTML = Arra ...

Obtaining the body from a post request in Node.js: A step-by-step guide

When sending data with the id using the post method to my node server, I encountered an issue where req.body is returning as undefined in my node file. This is what my index.html looks like: <html ng-app="IMDBApp"> <body> <div ng-contr ...

Using the tensorflow library with vite

Greetings and apologies for any inconvenience caused by my relatively trivial inquiries. I am currently navigating the introductory stages of delving into front-end development. Presently, I have initiated a hello-world vite app, which came to life throug ...

The Angular4 HTTP POST method fails to send data to the web API

Whenever I make a http post request, it keeps returning an error message saying "data does not pass correctly". I have tried passing the data through the body and also attempted using json.stringify(). Additionally, I experimented with setting the content ...

Error in Axios: The requested resource lacks the 'Access-Control-Allow-Origin' header

I'm having an issue sending form data to MongoDB using Axios in the frontend. The API works when I send a post request using Postman, but it fails when coming from the frontend. Here's a screenshot of the error: Frontend Code: const res = aw ...

Can you identify the type of component being passed in a Higher Order Component?

I am currently in the process of converting a protectedRoute HOC from Javascript to TypeScript while using AWS-Amplify. This higher-order component will serve as a way to secure routes that require authentication. If the user is not logged in, they will b ...

Exploring the potential of AssemblyScript in creating immersive WebXR

I have been exploring three.js and webXR for some time now, and I wanted to incorporate it into assembly script. While I know how to make webXR work in TypeScript, I encounter an error when trying to use it in assembly script with the import statement. Her ...

Is there a method to implement retries for inconsistent tests with jest-puppeteer?

Currently, I am struggling with an issue where there is no built-in method to retry flaky tests in Jest. My tech stack includes Jest + TypeScript + Puppeteer. Has anyone else encountered this problem or have any suggestions for possible solutions? I attem ...

Utilize jQuery post to send a request to a particular function located at a given URL

Is there a way to accomplish the following: $.post( "functions.php", { name: "John", time: "2pm" }) .done(function( data ) { alert( "Data Loaded: " + data ); }); Instead, is it possible to direct your data to a particular function in "functions.p ...

Encountering the ExpressionChangedAfterItHasBeenCheckedError error during Karma testing

Testing out some functionality in one of my components has led me to face an issue. I have set up an observable that is connected to the paramMap of the ActivatedRoute to retrieve a guid from the URL. This data is then processed using switchMap and assigne ...