node.js - How to check api response on regular interval after hitting it once - TagMerge
3How to check api response on regular interval after hitting it onceHow to check api response on regular interval after hitting it once

How to check api response on regular interval after hitting it once

Asked 1 years ago
0
3 answers

Given that is a third party API over which you have no control, unless they expose some sort of persistent socket connection, the short answer is NO.

At the moment, it seems like your only choice is to poll the API at a certain interval and check.

EDIT: If it is not required to send a response when status changes to ALLOWED, then you can perform CRON jobs as well, but the basic concept remains the same regardless, you're gonna have to hit the API at a certain interval to get updated values.

Source: link

0

In the following example, the browser will wait two seconds before executing the anonymous function, then will display the alert message (see it running live, and see the source code):
let myGreeting = setTimeout(() => {
  alert('Hello, Mr. Universe!');
}, 2000);
The functions you specify don't have to be anonymous. You can give your function a name, and even define it somewhere else and pass a function reference to the setTimeout(). The following two versions of the code snippet are equivalent to the first one:
// With a named function
let myGreeting = setTimeout(function sayHi() {
  alert('Hello, Mr. Universe!');
}, 2000);

// With a function defined separately
function sayHi() {
  alert('Hello Mr. Universe!');
}

let myGreeting = setTimeout(sayHi, 2000);
For example, you could refactor the previous function so that it will say hi to whatever person's name is passed to it:
function sayHi(who) {
  alert(`Hello ${who}!`);
}
Now, you can pass the name of the person into the setTimeout() call as a third parameter:
let myGreeting = setTimeout(sayHi, 2000, 'Mr. Universe');
Finally, if a timeout has been created, you can cancel it before the specified time has elapsed by calling clearTimeout(), passing it the identifier of the setTimeout() call as a parameter. So to cancel our above timeout, you'd do this:
clearTimeout(myGreeting);

Source: link

0

I created an interface to tell Typescript the data I expect.
export interface AuthResponseData {
  token: string;
  expires: string;
  role: number;
}
Then I created a method to send the login data to the server.
login(user: string, password: string){
  return this.http.post<AuthResponseData>(
    'https://localhost:44344/api/auth', { user: user, pwd: password }
  ).pipe(
    catchError(this.handleError),
    tap(resData => { this.handleAuthentication(resData.token, resData.expires, resData.role)})
  );
}
You can use promise and thenable() function to catch the error if your api response is not as per your requirement.
login(user: string, password: string){
        return this.http.post('https://localhost:44344/api/auth', { user: user, pwd: password })
        .pipe(map(response => {
            this.checkForValidResponse(response)
            .then( onResolve =>{
                //Came here is your response is according to your requirements
            })
            .catch(onReject =>{
                //Catch the error and treat it as error if your resposne is not according to your requirements
            });
        }));            
    }
    checkForValidResponse(responseOfApi){
        return new Promise((resolve, reject)=>{
            //Your Code for To Check wether API response is Valid OR not . 

            //If YOur API reponse is valid then **
            resolve(Your message to send back)

            //IF your API resopnse is invalid
            reject(Your message to send back)
        })
    }
e.g.
interface IAuthResponseData {
  token: string;
  expires: string;
  role: string;
}

class AuthResponseData implements IAuthResponseData {
  public token: string;
  public expires: string;
  private __expires: Date;
  public role: string;

  public constructor(data: IAuthResponseData) {
    this.token = data.token;
    this.expires = data.expires;
    this.__expires = new Date(data.expires);
    this.role = data.role;
    if (!this.isValid()) {
      throw new Error("Invalid Parameters")
    }
  }

  public isValid(): boolean {
    // simple equals check against null is also true when the value is undefined
    for (let member in this) {
      if (this[member] == null) {
        return false;
      }
    }
    return true;
  }
}
You can throw an error that would be catched by the catchError()
login(user: string, password: string){
  return this.http.post<AuthResponseData>(
    'https://localhost:44344/api/auth', { user: user, pwd: password }
  ).pipe(
    map(res => { //  Map should return an observable
      if(!this.isValid()) // isValid() is a hole diffrent story - stucture checking in tyepscript -
          throw new Error('Response structure is not valid.') // Would be catched by catchError
      return res;
    })
    tap(resData => { // tap is for side effects
        this.handleAuthentication(resData.token, resData.expires, resData.role)
    })
    catchError(this.handleError)
  );
}

Source: link

Recent Questions on node.js

    Programming Languages