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 };
});;
}
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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With