import { WyreAPIInterface } from './WyreAPIInterface' import { WyreAPIOptions } from './WyreAPIOptions' // tslint:disable: no-console const setTimer = async ms => new Promise(resolve => setTimeout(resolve, ms)) export class WyreAPIUtils { constructor( private options: WyreAPIOptions, private api: WyreAPIInterface, ) { } async waitForAccountToBeApproved({ accountID, maxWait = this.options.maxWait, retryInterval = this.options.retryInterval, }) { const fn = this.api.getAccountInfoV3.bind(this.api, accountID) const res = await this.waitForApproval(fn, 'APPROVED', maxWait, retryInterval) return res } async waitForPaymentMethodToBeApproved({ paymentMethodID, maxWait = this.options.maxWait, retryInterval = this.options.retryInterval, }) { const fn = this.api.getPaymentMethod.bind(this.api, paymentMethodID) const res = await this.waitForApproval(fn, 'ACTIVE', maxWait, retryInterval) return res } async waitForTransferToComplete({ transferID, maxWait = this.options.maxWait, retryInterval = this.options.retryInterval, }) { const fn = this.api.getTransfers.bind(this.api, transferID) const res = await this.waitForApproval(fn, 'COMPLETED', maxWait, retryInterval) return res } // eslint-disable-next-line class-methods-use-this async waitForApproval(fn, approvedStatus, maxWait, retryInterval) { let numRetries = 0 let waitPeriod let value let error do { // eslint-disable-next-line no-await-in-loop ({ response: value, error } = await fn()) if (error) { return { error } } if (value.status === approvedStatus) { break } else { numRetries++ waitPeriod = numRetries * retryInterval // if (numRetries % 30 === 0) { // console.log(`...waiting for approval elapsed time: ${waitPeriod / 1000} seconds`) // } // eslint-disable-next-line no-await-in-loop await setTimer(retryInterval) } } while (waitPeriod <= maxWait) // if (waitPeriod > maxWait) { // console.log(`waited ${waitPeriod / 1000} seconds for approval, failed to get it`) // } // if (numRetries > 1) { // console.log(`waited ${waitPeriod / 1000} seconds for approval`) // } return value } }