Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic handling of typescript promise response/errors

I have a number of functions that all perform the exact same action upon the return of a promise. this.client is a wrapper for a set of API calls, they return a response or an error. I wish to handle these in all the same manner.

Any ideas can I reduce each of these methods into one liners?

  getHealthCheck() {
    return this.client.tools.healthcheck().then((response) => {
      return {success: true, result: response};
    }).catch((err) => {
      return {success: false, err: err };
    });;
  }

  createUser(data) {

    return this.client.users.create(data).then((response) => {
      return {success: true, result: response};
    }).catch((err) => {
      return {success: false, err: err };
    });;

  }

  createCardAccount(data) {
    return this.client.cardAccounts.create(data).then((response) => {
      return {success: true, result: response};
    }).catch((err) => {
      return {success: false, err: err };
    });;
  }

  createBankAccount(data) {
    return this.client.bankAccounts.create(data).then((response) => {
      return {success: true, result: response};
    }).catch((err) => {
      return {success: false, err: err };
    });;
  }

  makePayment(data) {
    return this.client.items.makePayment(data).then((response) => {
      return {success: true, result: response};
    }).catch((err) => {
      return {success: false, err: err };
    });;
  }
like image 693
Phillip Hartin Avatar asked Oct 17 '25 02:10

Phillip Hartin


2 Answers

Why not just lift the response into another type:

type Success<T> = {success: true, result: T};
type Failure = {success: false, err: Error};
type Result<T> = Success<T> | Failure;
const Result = {
  from<T>(promise: Promise<T>): Promise<Result<T>> {
    return promise
           .then(result => ({success: true, result}))
           .catch(err => ({success: false, err}));
  }
}

Then you can use it as so:

return Result.from(this.client.tools.healthcheck());
like image 57
Sean Vieira Avatar answered Oct 18 '25 20:10

Sean Vieira


Your callbacks for success and error seems to be the same.. You could do:

successHandler = (response:any)=>{
     return {success: true, result: response};
     }
errorHandler = (error:any)=>{
     return {success: false, err: err };
     }

and for all your requests,

 getHealthCheck() {
    return this.client.tools.healthcheck().then(this.successHandler).catch(this.errorHandler);
  }

// other calls

Its DRY principle.

like image 24
Suraj Rao Avatar answered Oct 18 '25 21:10

Suraj Rao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!