Created
November 29, 2021 14:02
-
-
Save ziomarco/1b754f27237a710eac6450de46f72167 to your computer and use it in GitHub Desktop.
NestJS util in order to obtain "side-effects"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Little helper for creating "side effects" with TypeScript | |
* @param effect {Promise<T> | Function} Function or promise to call independently | |
* @param caller {string} Name of side effect, useful for logging | |
*/ | |
export function sideEffect(effect: Promise<any> | Function, caller: string): void { | |
if (effect instanceof Promise) { | |
effect | |
.then(() => console.log(`Side effect "${caller}" completed without errors.`)) | |
.catch((e) => console.log(`Side effect "${caller}" completed with errors: ${e.message || JSON.stringify(e)}`)); | |
return; | |
} | |
if (effect instanceof Function) { | |
try { | |
effect(); | |
console.log(`Side effect "${caller}" completed without errors.`) | |
} catch (e) { | |
console.log(`Side effect "${caller}" completed with errors: ${e.message || JSON.stringify(e)}`) | |
} | |
return; | |
} | |
console.log(`Side effect "${caller}" completed with errors: (given arg) is not a promise neither a function!`); | |
} | |
// Example usage: | |
// In this case {status: true} will be returned exactly after await markUserCartAsCompleted and deleteCustomerPaymentMethod will be executed "in background" | |
await this.guestcartDatabase.markUserCartAsCompleted(req.guestCartId); | |
if (req.nativePaymentToken) { | |
sideEffect(this.stripeService.deleteCustomerPaymentMethod(firebaseToken, stripe_token.split(':')[0]), "ORDER_DELETE_CUSTOMER_PM"); | |
} | |
return { status: true }; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment