diff --git a/src/Client.ts b/src/Client.ts index e38ea96..19c400c 100644 --- a/src/Client.ts +++ b/src/Client.ts @@ -1,5 +1,5 @@ import { ec } from 'elliptic'; -import { BitPayExceptions as Exceptions, Env, Facade, KeyUtils } from './index'; +import { Env, Facade, KeyUtils } from './index'; import { BillInterface, InvoiceInterface, @@ -12,31 +12,34 @@ import { RateInterface, Rates } from './Model'; -import { BitPayClient } from './Client/BitPayClient'; +import { + BitPayClient, + RateClient, + CurrencyClient, + InvoiceClient, + RefundClient, + PayoutClient, + PayoutGroupClient, + PayoutRecipientClient, + LedgerClient, + BillClient, + WalletClient, + SettlementClient +} from './Client/index'; + import { TokenContainer } from './TokenContainer'; import { Environment } from './Environment'; -import BitPayException from './Exceptions/BitPayException'; import { GuidGenerator } from './util/GuidGenerator'; -import { RateClient } from './Client/RateClient'; -import { CurrencyClient } from './Client/CurrencyClient'; -import { InvoiceClient } from './Client/InvoiceClient'; import { InvoiceEventTokenInterface } from './Model/Invoice/InvoiceEventToken'; import { RefundInterface } from './Model/Invoice/Refund'; -import { RefundClient } from './Client/RefundClient'; -import { PayoutRecipientClient } from './Client/PayoutRecipientClient'; -import { PayoutClient } from './Client/PayoutClient'; -import { LedgerClient } from './Client/LedgerClient'; import { ParamsRemover } from './util/ParamsRemover'; -import { BillClient } from './Client/BillClient'; import { WalletInterface } from './Model/Wallet/Wallet'; -import { WalletClient } from './Client/WalletClient'; import { SettlementInterface } from './Model/Settlement/Settlement'; -import { SettlementClient } from './Client/SettlementClient'; import { PosToken } from './PosToken'; import { PrivateKey } from './PrivateKey'; import { CurrencyInterface } from './Model/Currency/Currency'; - import * as fs from 'fs'; +import { BitPayExceptionProvider } from './Exceptions/BitPayExceptionProvider'; export class Client { private bitPayClient: BitPayClient; @@ -59,16 +62,16 @@ export class Client { return; } + if (tokenContainer === null) { + tokenContainer = new TokenContainer(); + } + if (bitPayClient !== undefined && bitPayClient !== null) { // using for tests this.initForTests(bitPayClient, guidGenerator, tokenContainer); return; } - if (tokenContainer === null) { - tokenContainer = new TokenContainer(); - } - if (environment === undefined) { environment = Environment.Prod; } @@ -515,7 +518,7 @@ export class Client { * @param payouts */ public async submitPayouts(payouts: PayoutInterface[]): Promise { - return this.createPayoutClient().submitPayouts(payouts); + return this.createPayoutGroupClient().submitPayouts(payouts); } /** @@ -524,7 +527,7 @@ export class Client { * @param payoutGroupId */ public async cancelPayouts(payoutGroupId: string): Promise { - return this.createPayoutClient().cancelPayouts(payoutGroupId); + return this.createPayoutGroupClient().cancelPayouts(payoutGroupId); } /** @@ -731,7 +734,7 @@ export class Client { return this.keyUtils.load_keypair(Buffer.from(keyHex).toString().trim()); } - throw new BitPayException(null, 'Missing ECKey'); + BitPayExceptionProvider.throwGenericExceptionWithMessage('Missing ECKey'); } private static getBaseUrl(environment: string) { @@ -742,43 +745,47 @@ export class Client { return this.keyUtils.getPublicKeyFromPrivateKey(ecKey); } - private createRateClient() { + private createRateClient(): RateClient { return new RateClient(this.bitPayClient); } - private getCurrencyClient() { + private getCurrencyClient(): CurrencyClient { return new CurrencyClient(this.bitPayClient); } - private createInvoiceClient() { + private createInvoiceClient(): InvoiceClient { return new InvoiceClient(this.bitPayClient, this.tokenContainer, this.guidGenerator); } - private createRefundClient() { + private createRefundClient(): RefundClient { return new RefundClient(this.bitPayClient, this.tokenContainer, this.guidGenerator); } - private createPayoutRecipientClient() { + private createPayoutRecipientClient(): PayoutRecipientClient { return new PayoutRecipientClient(this.bitPayClient, this.tokenContainer, this.guidGenerator); } - private createPayoutClient() { + private createPayoutClient(): PayoutClient { return new PayoutClient(this.bitPayClient, this.tokenContainer, this.guidGenerator); } - private createLedgerClient() { + private createPayoutGroupClient(): PayoutGroupClient { + return new PayoutGroupClient(this.bitPayClient, this.tokenContainer, this.guidGenerator); + } + + private createLedgerClient(): LedgerClient { return new LedgerClient(this.bitPayClient, this.tokenContainer); } - private createBillClient() { + private createBillClient(): BillClient { return new BillClient(this.bitPayClient, this.tokenContainer); } - private createWalletClient() { + private createWalletClient(): WalletClient { return new WalletClient(this.bitPayClient); } - private createSettlementClient() { + private createSettlementClient(): SettlementClient { return new SettlementClient(this.bitPayClient, this.tokenContainer); } @@ -800,7 +807,7 @@ export class Client { private initByConfigFilePath(configFilePath: string): void { if (!fs.existsSync(configFilePath)) { - throw new Exceptions.Generic(null, 'Configuration file not found'); + BitPayExceptionProvider.throwGenericExceptionWithMessage('Configuration file not found'); } try { @@ -813,7 +820,7 @@ export class Client { this.bitPayClient = new BitPayClient(Client.getBaseUrl(environment), ecKey, this.getIdentity(ecKey)); this.guidGenerator = new GuidGenerator(); } catch (e) { - throw new Exceptions.Generic(null, 'Error when reading configuration file', null, e.apiCode); + BitPayExceptionProvider.throwGenericExceptionWithMessage('Error when reading configuration file'); } } diff --git a/src/Client/BillClient.ts b/src/Client/BillClient.ts index 60e0393..2a8d9ad 100644 --- a/src/Client/BillClient.ts +++ b/src/Client/BillClient.ts @@ -2,7 +2,7 @@ import { BitPayClient } from './BitPayClient'; import { TokenContainer } from '../TokenContainer'; import { BillInterface } from '../Model'; import { Facade } from '../Facade'; -import { BitPayExceptions as Exceptions } from '../index'; +import { BitPayExceptionProvider } from '../Exceptions/BitPayExceptionProvider'; export class BillClient { private bitPayClient: BitPayClient; @@ -20,19 +20,17 @@ export class BillClient { * @param facade The facade used to create it. * @param signRequest Signed request. * @returns Bill - * @throws BillCreationException + * @throws BitPayGenericException BitPayGenericException + * @throws BitPayApiException BitPayApiException */ public async create(bill: BillInterface, facade: string, signRequest: boolean): Promise { bill.token = this.tokenContainer.getToken(facade); + const result = await this.bitPayClient.post('bills', bill, signRequest); try { - const result = await this.bitPayClient.post('bills', bill, signRequest); return JSON.parse(result); } catch (e) { - throw new Exceptions.BillCreation( - 'failed to deserialize BitPay server response (Bill) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwSerializeResourceException('Bill', e.message); } } @@ -43,16 +41,17 @@ export class BillClient { * @param facade The facade used to retrieve it. * @param signRequest Signed request * @returns Bill - * @throws BillQueryException + * @throws BitPayGenericException BitPayGenericException class + * @throws BitPayApiException BitPayApiException class */ public async get(billId: string, facade: string, signRequest: boolean): Promise { const params = { token: this.tokenContainer.getToken(facade) }; + const result = await this.bitPayClient.get('bills/' + billId, params, signRequest); try { - const result = await this.bitPayClient.get('bills/' + billId, params, signRequest); return JSON.parse(result); } catch (e) { - throw new Exceptions.BillQuery('failed to deserialize BitPay server response (Bill) : ' + e.message, e.apiCode); + BitPayExceptionProvider.throwDeserializeResourceException('Bill', e.message); } } @@ -61,7 +60,8 @@ export class BillClient { * * @param status * @returns Bill[] - * @throws BillQueryException + * @throws BitPayGenericException BitPayGenericException + * @throws BitPayApiException BitPayApiException */ public async getBills(status: string | null): Promise { const params = { token: this.tokenContainer.getToken(Facade.Merchant) }; @@ -69,11 +69,12 @@ export class BillClient { params['status'] = status; } + const result = await this.bitPayClient.get('bills', params, true); + try { - const result = await this.bitPayClient.get('bills', params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.BillQuery('failed to deserialize BitPay server response (Bill) : ' + e.message, e.apiCode); + BitPayExceptionProvider.throwDeserializeResourceException('Bill', e.message); } } @@ -83,14 +84,16 @@ export class BillClient { * @param bill * @param billId * @returns Bill - * @throws BillUpdateException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async update(bill: BillInterface, billId: string): Promise { + const result = await this.bitPayClient.put('bills/' + billId, bill); + try { - const result = await this.bitPayClient.put('bills/' + billId, bill); return JSON.parse(result); } catch (e) { - throw new Exceptions.BillUpdate('failed to deserialize BitPay server response (Bill) : ' + e.message, e.apiCode); + BitPayExceptionProvider.throwDeserializeResourceException('Bill', e.message); } } @@ -101,19 +104,17 @@ export class BillClient { * @param billToken * @param signRequest * @returns string - * @throws BillDeliveryException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async deliver(billId: string, billToken: string, signRequest: boolean): Promise { const params = { token: billToken }; + const result = await this.bitPayClient.post('bills/' + billId + '/deliveries', params, signRequest); try { - const result = await this.bitPayClient.post('bills/' + billId + '/deliveries', params, signRequest); return JSON.parse(result) == 'Success'; } catch (e) { - throw new Exceptions.BillDelivery( - 'failed to deserialize BitPay server response (Bill) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Bill', e.message); } } } diff --git a/src/Client/BitPayClient.ts b/src/Client/BitPayClient.ts index 457aab2..59c0417 100644 --- a/src/Client/BitPayClient.ts +++ b/src/Client/BitPayClient.ts @@ -6,6 +6,8 @@ import KeyPair = ec.KeyPair; import * as qs from 'querystring'; import BitPayException from '../Exceptions/BitPayException'; import { BitPayResponseParser } from '../util/BitPayResponseParser'; +import { BitPayExceptionProvider } from '../Exceptions/BitPayExceptionProvider'; +import { LoggerProvider } from '../Logger/LoggerProvider'; export class BitPayClient { private readonly ecKey: KeyPair; @@ -52,21 +54,26 @@ export class BitPayClient { headers = this.getSignatureHeaders(fullUrl, headers, null); } - const result = await fetch(fullUrl, { - method: 'get', + const method = 'GET'; + + LoggerProvider.getLogger().logRequest(method, fullUrl, null); + + const response = await fetch(fullUrl, { + method: method, headers: headers }); - return this.responseParser.responseToJsonString(result); + const jsonObject = await response.json(); + + LoggerProvider.getLogger().logResponse(method, fullUrl, JSON.stringify(jsonObject)); + + return this.responseParser.getJsonDataFromJsonResponse(jsonObject); } catch (e) { - let message; if (e instanceof BitPayException) { - message = e.message; - } else { - message = e.response.data; + throw e; } - throw new BitPayException(null, 'GET failed : ' + JSON.stringify(message)); + BitPayExceptionProvider.throwApiExceptionWithMessage(JSON.stringify(e.message), null); } } @@ -87,21 +94,25 @@ export class BitPayClient { headers = this.getSignatureHeaders(fullUrl, headers, formData); } - const result = await fetch(fullUrl, { - method: 'post', + const method = 'POST'; + + const response = await fetch(fullUrl, { + method: method, headers: headers, body: formData }); - return this.responseParser.responseToJsonString(result); + + const jsonObject = await response.json(); + + LoggerProvider.getLogger().logResponse(method, fullUrl, JSON.stringify(jsonObject)); + + return this.responseParser.getJsonDataFromJsonResponse(jsonObject); } catch (e) { - let message: string; if (e instanceof BitPayException) { - message = e.message; - } else { - message = e.response.data; + throw e; } - throw new BitPayException(null, 'Post failed : ' + JSON.stringify(message)); + BitPayExceptionProvider.throwApiExceptionWithMessage(JSON.stringify(e.message), null); } } @@ -123,21 +134,25 @@ export class BitPayClient { headers = this.getSignatureHeaders(fullUrl, headers, formData); } - const result = await fetch(fullUrl, { - method: 'PUT', + const method = 'PUT'; + + const response = await fetch(fullUrl, { + method: method, headers: headers, body: formData }); - return this.responseParser.responseToJsonString(result); + + const jsonObject = await response.json(); + + LoggerProvider.getLogger().logResponse(method, fullUrl, JSON.stringify(jsonObject)); + + return this.responseParser.getJsonDataFromJsonResponse(jsonObject); } catch (e) { - let message: string; if (e instanceof BitPayException) { - message = e.message; - } else { - message = e.response.data; + throw e; } - throw new BitPayException(null, 'Put failed : ' + JSON.stringify(message)); + BitPayExceptionProvider.throwApiExceptionWithMessage(JSON.stringify(e.message), null); } } @@ -158,20 +173,24 @@ export class BitPayClient { headers = this.getSignatureHeaders(fullUrl, headers, null); } - const result = await fetch(fullUrl, { - method: 'delete', + const method = 'DELETE'; + + const response = await fetch(fullUrl, { + method: method, headers: headers }); - return this.responseParser.responseToJsonString(result); + + const jsonObject = await response.json(); + + LoggerProvider.getLogger().logResponse(method, fullUrl, JSON.stringify(jsonObject)); + + return this.responseParser.getJsonDataFromJsonResponse(jsonObject); } catch (e) { - let message: string; if (e instanceof BitPayException) { - message = e.message; - } else { - message = e.response.data; + throw e; } - throw new BitPayException(null, 'Delete failed : ' + JSON.stringify(message)); + BitPayExceptionProvider.throwApiExceptionWithMessage(JSON.stringify(e.message), null); } } @@ -180,14 +199,18 @@ export class BitPayClient { * @param fullUrl * @param headers * @param jsonData - * @returns + * @throws BitPayApiExtension */ private getSignatureHeaders(fullUrl: string, headers: object, jsonData: string) { if (jsonData !== null) { fullUrl = fullUrl + jsonData; } - headers['X-Signature'] = this.keyUtils.sign(fullUrl, this.ecKey); + try { + headers['X-Signature'] = this.keyUtils.sign(fullUrl, this.ecKey); + } catch (e) { + BitPayExceptionProvider.throwGenericExceptionWithMessage('Wrong ecKey. ' + e.message); + } headers['X-Identity'] = this.identity; return headers; diff --git a/src/Client/InvoiceClient.ts b/src/Client/InvoiceClient.ts index 48459ec..6be2e42 100644 --- a/src/Client/InvoiceClient.ts +++ b/src/Client/InvoiceClient.ts @@ -1,10 +1,11 @@ import { BitPayClient } from './BitPayClient'; import { Invoice, InvoiceInterface } from '../Model'; -import { BitPayExceptions as Exceptions, Facade } from '../index'; import { TokenContainer } from '../TokenContainer'; import { GuidGenerator } from '../util/GuidGenerator'; import { InvoiceEventTokenInterface } from '../Model/Invoice/InvoiceEventToken'; import { BitPayResponseParser } from '../util/BitPayResponseParser'; +import { BitPayExceptionProvider } from '../Exceptions/BitPayExceptionProvider'; +import { Facade } from '../Facade'; export class InvoiceClient { private bitPayClient: BitPayClient; @@ -24,20 +25,19 @@ export class InvoiceClient { * @param facade The facade used to create it. * @param signRequest Signed request. * @returns Invoice - * @throws InvoiceCreationException. + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async create(invoice: Invoice, facade: Facade, signRequest: boolean): Promise { invoice.guid = invoice.guid ? invoice.guid : this.guidGenerator.execute(); invoice.token = this.tokenContainer.getToken(facade); + const result = await this.bitPayClient.post('invoices', invoice, signRequest); + try { - const result = await this.bitPayClient.post('invoices', invoice, signRequest); return JSON.parse(result); } catch (e) { - throw new Exceptions.InvoiceCreation( - 'failed to deserialize BitPay server response (Invoice) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Invoice', e.message); } } @@ -49,19 +49,18 @@ export class InvoiceClient { * @param facade The facade used to create it. * @param signRequest Signed request. * @returns Invoice - * @throws InvoiceQueryException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async get(invoiceId: string, facade: Facade, signRequest: boolean): Promise { const params = { token: this.tokenContainer.getToken(facade) }; + const result = await this.bitPayClient.get('invoices/' + invoiceId, params, signRequest); + try { - const result = await this.bitPayClient.get('invoices/' + invoiceId, params, signRequest); return JSON.parse(result); } catch (e) { - throw new Exceptions.InvoiceQuery( - 'failed to deserialize BitPay server response (Invoice) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Invoice', e.message); } } @@ -70,19 +69,18 @@ export class InvoiceClient { * @param facade * @param signRequest * @returns Invoice - * @throws InvoiceQueryException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async getByGuid(guid: string, facade: Facade, signRequest: boolean): Promise { const params = { token: this.tokenContainer.getToken(facade) }; + const result = await this.bitPayClient.get('invoices/guid/' + guid, params, signRequest); + try { - const result = await this.bitPayClient.get('invoices/guid/' + guid, params, signRequest); return JSON.parse(result); } catch (e) { - throw new Exceptions.InvoiceQuery( - 'failed to deserialize BitPay server response (Invoice) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Invoice', e.message); } } @@ -91,19 +89,18 @@ export class InvoiceClient { * * @param params * @returns Invoice[] - * @throws InvoiceQueryException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async getInvoices(params: object): Promise { params['token'] = this.tokenContainer.getToken(Facade.Merchant); + const result = await this.bitPayClient.get('invoices', params, true); + try { - const result = await this.bitPayClient.get('invoices', params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.InvoiceQuery( - 'failed to deserialize BitPay server response (Invoice) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Invoice', e.message); } } @@ -116,14 +113,12 @@ export class InvoiceClient { const params = {}; params['token'] = this.tokenContainer.getToken(Facade.Merchant); + const result = await this.bitPayClient.get('invoices/' + invoiceId + '/events', params, true); + try { - const result = await this.bitPayClient.get('invoices/' + invoiceId + '/events', params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.InvoiceQuery( - 'failed to deserialize BitPay server response (Invoice) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Invoice', e.message); } } @@ -133,19 +128,18 @@ export class InvoiceClient { * @param invoiceId The id of the invoice to updated. * @param params * @returns Invoice - * @throws InvoiceUpdateException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async update(invoiceId: string, params: []): Promise { params['token'] = this.tokenContainer.getToken(Facade.Merchant); + const result = await this.bitPayClient.put('invoices/' + invoiceId, params); + try { - const result = await this.bitPayClient.put('invoices/' + invoiceId, params); return JSON.parse(result); } catch (e) { - throw new Exceptions.InvoiceUpdate( - 'failed to deserialize BitPay server response (Invoice) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Invoice', e.message); } } @@ -155,22 +149,20 @@ export class InvoiceClient { * @param invoiceId The id of the invoice. * @param status Status the invoice will become. Acceptable values are confirmed (default) and complete. * @returns Invoice Invoice object. - * @throws BitPayException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async pay(invoiceId: string, status: string): Promise { const params = { token: this.tokenContainer.getToken(Facade.Merchant), status: status }; + const result = await this.bitPayClient.put('invoices/pay/' + invoiceId, params); try { - const result = await this.bitPayClient.put('invoices/pay/' + invoiceId, params); return JSON.parse(result); } catch (e) { - throw new Exceptions.InvoiceGeneric( - 'failed to deserialize BitPay server response (Invoice) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Invoice', e.message); } } @@ -180,22 +172,20 @@ export class InvoiceClient { * @param invoiceId The id of the invoice to updated. * @param forceCancel * @returns Invoice Cancelled invoice object. - * @throws BitPayException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async cancel(invoiceId: string, forceCancel: boolean): Promise { const params = { token: this.tokenContainer.getToken(Facade.Merchant), forceCancel: forceCancel }; + const result = await this.bitPayClient.delete('invoices/' + invoiceId, params); try { - const result = await this.bitPayClient.delete('invoices/' + invoiceId, params); return JSON.parse(result); } catch (e) { - throw new Exceptions.InvoiceGeneric( - 'failed to deserialize BitPay server response (Invoice) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Invoice', e.message); } } @@ -205,22 +195,20 @@ export class InvoiceClient { * @param guid The guid of the invoice to cancel. * @param forceCancel * @returns Invoice Cancelled invoice object. - * @throws BitPayException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async cancelByGuid(guid: string, forceCancel: boolean): Promise { const params = { token: this.tokenContainer.getToken(Facade.Merchant), forceCancel: forceCancel }; + const result = await this.bitPayClient.delete('invoices/guid/' + guid, params); try { - const result = await this.bitPayClient.delete('invoices/guid/' + guid, params); return JSON.parse(result); } catch (e) { - throw new Exceptions.InvoiceGeneric( - 'failed to deserialize BitPay server response (Invoice) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Invoice', e.message); } } @@ -229,19 +217,17 @@ export class InvoiceClient { * * @param invoiceId A BitPay invoice ID. * @returns boolean - * @throws BitPayException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async requestInvoiceWebhookToBeResent(invoiceId: string): Promise { const params = { token: this.tokenContainer.getToken(Facade.Merchant) }; + const result = await this.bitPayClient.post('invoices/' + invoiceId + '/notifications', params); try { - const result = await this.bitPayClient.post('invoices/' + invoiceId + '/notifications', params); return BitPayResponseParser.jsonToBoolean(result); } catch (e) { - throw new Exceptions.InvoiceGeneric( - 'failed to deserialize BitPay server response (Invoice) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Invoice', e.message); } } } diff --git a/src/Client/LedgerClient.ts b/src/Client/LedgerClient.ts index f7b7a01..e6fb485 100644 --- a/src/Client/LedgerClient.ts +++ b/src/Client/LedgerClient.ts @@ -2,7 +2,7 @@ import { BitPayClient } from './BitPayClient'; import { TokenContainer } from '../TokenContainer'; import { LedgerEntryInterface, LedgerInterface } from '../Model'; import { Facade } from '../Facade'; -import { BitPayExceptions as Exceptions } from '../index'; +import { BitPayExceptionProvider } from '../Exceptions/BitPayExceptionProvider'; export class LedgerClient { private bitPayClient: BitPayClient; @@ -17,19 +17,17 @@ export class LedgerClient { * Retrieve a list of ledgers using the merchant facade. * * @return A list of Ledger objects populated with the currency and current balance of each one. - * @throws LedgerQueryException LedgerQueryException class + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async getLedgers(): Promise { const params = { token: this.tokenContainer.getToken(Facade.Merchant) }; + const result = await this.bitPayClient.get('ledgers', params, true); try { - const result = await this.bitPayClient.get('ledgers', params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.LedgerQuery( - 'failed to deserialize BitPay server response (Ledger) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Ledger', e.message); } } @@ -39,19 +37,18 @@ export class LedgerClient { * @param currency * @param params * @returns ledgers - * @throws LedgerQueryException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async getEntries(currency: string, params: object): Promise { params['token'] = this.tokenContainer.getToken(Facade.Merchant); + const result = await this.bitPayClient.get('ledgers/' + currency, params, true); + try { - const result = await this.bitPayClient.get('ledgers/' + currency, params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.LedgerQuery( - 'failed to deserialize BitPay server response (Ledger) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Ledger', e.message); } } } diff --git a/src/Client/PayoutClient.ts b/src/Client/PayoutClient.ts index 75ee1ab..3c8bc30 100644 --- a/src/Client/PayoutClient.ts +++ b/src/Client/PayoutClient.ts @@ -2,10 +2,9 @@ import { BitPayClient } from './BitPayClient'; import { TokenContainer } from '../TokenContainer'; import { GuidGenerator } from '../util/GuidGenerator'; import { Facade } from '../Facade'; -import { BitPayExceptions as Exceptions } from '../index'; import { PayoutInterface } from '../Model'; import { BitPayResponseParser } from '../util/BitPayResponseParser'; -import { PayoutGroup, PayoutGroupInterface } from '../Model/Payout/PayoutGroup'; +import { BitPayExceptionProvider } from '../Exceptions/BitPayExceptionProvider'; export class PayoutClient { private bitPayClient: BitPayClient; @@ -22,20 +21,17 @@ export class PayoutClient { * Submit a BitPay Payout. * * @param payout Payout object with request parameters defined. - * @returns Pyaout + * @returns Payout * @throws PayoutCreationException */ public async submit(payout: PayoutInterface): Promise { payout.token = this.tokenContainer.getToken(Facade.Payout); + const result = await this.bitPayClient.post('payouts', payout, true); try { - const result = await this.bitPayClient.post('payouts', payout, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.PayoutCreation( - 'failed to deserialize BitPay server response (Payout) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Payout', e.message); } } @@ -44,20 +40,17 @@ export class PayoutClient { * for the payout facade. * * @param payoutId The id of the payout to retrieve. - * @returns Pyaout + * @returns Payout * @throws PayoutQueryException */ public async get(payoutId: string): Promise { const params = { token: this.tokenContainer.getToken(Facade.Payout) }; + const result = await this.bitPayClient.get('payouts/' + payoutId, params, true); try { - const result = await this.bitPayClient.get('payouts/' + payoutId, params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.PayoutQuery( - 'failed to deserialize BitPay server response (Payout) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Payout', e.message); } } @@ -70,15 +63,12 @@ export class PayoutClient { */ public async getPayouts(params: object): Promise { params['token'] = this.tokenContainer.getToken(Facade.Payout); + const result = await this.bitPayClient.get('payouts', params, true); try { - const result = await this.bitPayClient.get('payouts', params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.PayoutQuery( - 'failed to deserialize BitPay server response (Payout) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Payout', e.message); } } @@ -91,15 +81,12 @@ export class PayoutClient { */ public requestNotification = async (payoutId: string): Promise => { const params = { token: this.tokenContainer.getToken(Facade.Payout) }; + const result = await this.bitPayClient.post('payouts/' + payoutId + '/notifications', params, true); try { - const result = await this.bitPayClient.post('payouts/' + payoutId + '/notifications', params, true); return BitPayResponseParser.jsonToBoolean(result); } catch (e) { - throw new Exceptions.PayoutNotification( - 'failed to deserialize BitPay server response (Payout) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Payout', e.message); } }; @@ -112,51 +99,12 @@ export class PayoutClient { */ public cancel = async (payoutId: string): Promise => { const params = { token: this.tokenContainer.getToken(Facade.Payout) }; + const result = await this.bitPayClient.delete('payouts/' + payoutId, params, true); try { - const result = await this.bitPayClient.delete('payouts/' + payoutId, params, true); return BitPayResponseParser.jsonToBoolean(result); } catch (e) { - throw new Exceptions.PayoutDelete( - 'failed to deserialize BitPay server response (Payout) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Payout', e.message); } }; - - submitPayouts = async (payouts: PayoutInterface[]): Promise => { - const params = { token: this.tokenContainer.getToken(Facade.Payout), instructions: payouts }; - try { - const result = await this.bitPayClient.post('payouts/group', params, true); - return PayoutClient.getPayoutGroupResponse(result, 'created'); - } catch (e) { - throw new Exceptions.PayoutCreation( - 'failed to deserialize BitPay server response (Payout) : ' + e.message, - e.apiCode - ); - } - }; - - cancelPayouts = async (payoutGroupId: string) => { - const params = { token: this.tokenContainer.getToken(Facade.Payout) }; - try { - const result = await this.bitPayClient.delete('payouts/group/' + payoutGroupId, params, true); - return PayoutClient.getPayoutGroupResponse(result, 'cancelled'); - } catch (e) { - throw new Exceptions.PayoutCreation( - 'failed to deserialize BitPay server response (Payout) : ' + e.message, - e.apiCode - ); - } - }; - - private static getPayoutGroupResponse(json: string, responseType: string): PayoutGroupInterface { - const response = JSON.parse(json); - - if (!(responseType in response)) { - throw new Exceptions.PayoutCreation('Cannot parse Payout Group. Response : ' + response); - } - - return new PayoutGroup(response[responseType], response['failed']); - } } diff --git a/src/Client/PayoutGroupClient.ts b/src/Client/PayoutGroupClient.ts new file mode 100644 index 0000000..1eacc67 --- /dev/null +++ b/src/Client/PayoutGroupClient.ts @@ -0,0 +1,55 @@ +import { BitPayClient } from './BitPayClient'; +import { TokenContainer } from '../TokenContainer'; +import { GuidGenerator } from '../util/GuidGenerator'; +import { PayoutGroupInterface, PayoutInterface } from '../Model'; +import { Facade } from '../Facade'; +import { BitPayExceptionProvider } from '../Exceptions/BitPayExceptionProvider'; +import { PayoutGroup } from '../Model/Payout/PayoutGroup'; + +export class PayoutGroupClient { + private bitPayClient: BitPayClient; + private tokenContainer: TokenContainer; + private guidGenerator: GuidGenerator; + + constructor(bitPayClient: BitPayClient, tokenContainer: TokenContainer, guidGenerator: GuidGenerator) { + this.bitPayClient = bitPayClient; + this.tokenContainer = tokenContainer; + this.guidGenerator = guidGenerator; + } + + /** + * + * @param payouts + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class + */ + submitPayouts = async (payouts: PayoutInterface[]): Promise => { + const params = { token: this.tokenContainer.getToken(Facade.Payout), instructions: payouts }; + const result = await this.bitPayClient.post('payouts/group', params, true); + + return PayoutGroupClient.getPayoutGroupResponse(result, 'created'); + }; + + /** + * + * @param payoutGroupId + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class + */ + cancelPayouts = async (payoutGroupId: string) => { + const params = { token: this.tokenContainer.getToken(Facade.Payout) }; + const result = await this.bitPayClient.delete('payouts/group/' + payoutGroupId, params, true); + + return PayoutGroupClient.getPayoutGroupResponse(result, 'cancelled'); + }; + + private static getPayoutGroupResponse(json: string, responseType: string): PayoutGroupInterface { + const response = JSON.parse(json); + + if (!(responseType in response)) { + BitPayExceptionProvider.throwDeserializeResourceException('Payout Group', response); + } + + return new PayoutGroup(response[responseType], response['failed']); + } +} diff --git a/src/Client/PayoutRecipientClient.ts b/src/Client/PayoutRecipientClient.ts index cdd7c17..42b4582 100644 --- a/src/Client/PayoutRecipientClient.ts +++ b/src/Client/PayoutRecipientClient.ts @@ -2,8 +2,9 @@ import { BitPayClient } from './BitPayClient'; import { TokenContainer } from '../TokenContainer'; import { GuidGenerator } from '../util/GuidGenerator'; import { PayoutRecipientInterface, PayoutRecipients } from '../Model'; -import { BitPayExceptions as Exceptions, Facade } from '../index'; import { BitPayResponseParser } from '../util/BitPayResponseParser'; +import { BitPayExceptionProvider } from '../Exceptions/BitPayExceptionProvider'; +import { Facade } from '../index'; export class PayoutRecipientClient { private bitPayClient: BitPayClient; @@ -21,20 +22,18 @@ export class PayoutRecipientClient { * * @param recipients A PayoutRecipients object with request parameters defined. * @returns PayoutRecipients[] A list of BitPay PayoutRecipients objects. - * @throws PayoutRecipientCreationException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async submit(recipients: PayoutRecipients): Promise { recipients.token = this.tokenContainer.getToken(Facade.Payout); recipients.guid = recipients.guid ? recipients.guid : this.guidGenerator.execute(); + const result = await this.bitPayClient.post('recipients', recipients, true); try { - const result = await this.bitPayClient.post('recipients', recipients, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.PayoutRecipientCreation( - 'failed to deserialize BitPay server response (Invoice) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Payout Recipient', e.message); } } @@ -44,20 +43,19 @@ export class PayoutRecipientClient { * @param recipientId The recipient id for the recipient to be updated. * @param recipient A PayoutRecipient object with updated parameters defined. * @returns PayoutRecipient - * @throws PayoutRecipientUpdateException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async update(recipientId: string, recipient: PayoutRecipientInterface): Promise { recipient.token = this.tokenContainer.getToken(Facade.Payout); recipient.guid = recipient.guid ? recipient.guid : this.guidGenerator.execute(); + const result = await this.bitPayClient.put('recipients/' + recipientId, recipient, true); + try { - const result = await this.bitPayClient.put('recipients/' + recipientId, recipient, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.PayoutRecipientUpdate( - 'failed to deserialize BitPay server response (PayoutRecipient) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Payout Recipient', e.message); } } @@ -66,19 +64,18 @@ export class PayoutRecipientClient { * * @param recipientId The id of the recipient to retrieve. * @returns PayoutRecipient - * @throws PayoutRecipientQueryException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async get(recipientId: string): Promise { const params = { token: this.tokenContainer.getToken(Facade.Payout) }; + const result = await this.bitPayClient.get('recipients/' + recipientId, params, true); + try { - const result = await this.bitPayClient.get('recipients/' + recipientId, params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.PayoutRecipientQuery( - 'failed to deserialize BitPay server response (PayoutRecipient) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Payout Recipient', e.message); } } @@ -87,19 +84,18 @@ export class PayoutRecipientClient { * * @param params * @returns PayoutRecipient[] - * @throws PayoutRecipientQueryException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async getByFilters(params: object): Promise { - try { - params['token'] = this.tokenContainer.getToken(Facade.Payout); + params['token'] = this.tokenContainer.getToken(Facade.Payout); - const result = await this.bitPayClient.get('recipients', params, true); + const result = await this.bitPayClient.get('recipients', params, true); + + try { return JSON.parse(result); } catch (e) { - throw new Exceptions.PayoutRecipientQuery( - 'failed to deserialize BitPay server response (PayoutRecipients) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Payout Recipient', e.message); } } @@ -108,19 +104,17 @@ export class PayoutRecipientClient { * * @param recipientId The recipient id for the recipient to be deleted. * @returns boolean True if the recipient was successfully deleted, false otherwise. - * @throws PayoutRecipientCancellationException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async delete(recipientId: string): Promise { const params = { token: this.tokenContainer.getToken(Facade.Payout) }; + const result = await this.bitPayClient.delete('recipients/' + recipientId, params, true); try { - const result = await this.bitPayClient.delete('recipients/' + recipientId, params, true); return BitPayResponseParser.jsonToBoolean(result); } catch (e) { - throw new Exceptions.PayoutRecipientCancellation( - 'failed to deserialize BitPay server response (PayoutRecipient) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Payout Recipient', e.message); } } @@ -129,19 +123,18 @@ export class PayoutRecipientClient { * * @param recipientId The id of the recipient to notify. * @returns boolean True if the notification was successfully sent, false otherwise. - * @throws PayoutRecipientNotificationException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async requestNotification(recipientId: string): Promise { const params = { token: this.tokenContainer.getToken(Facade.Payout) }; + const result = await this.bitPayClient.post('recipients/' + recipientId + '/notifications', params, true); + try { - const result = await this.bitPayClient.post('recipients/' + recipientId + '/notifications', params, true); return BitPayResponseParser.jsonToBoolean(result); } catch (e) { - throw new Exceptions.PayoutRecipientNotification( - 'failed to deserialize BitPay server response (PayoutRecipient) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Payout Recipient', e.message); } } } diff --git a/src/Client/RateClient.ts b/src/Client/RateClient.ts index b17450c..346dac3 100644 --- a/src/Client/RateClient.ts +++ b/src/Client/RateClient.ts @@ -1,6 +1,6 @@ import { RateInterface, Rates } from '../Model'; import { BitPayClient } from './BitPayClient'; -import { BitPayExceptions as Exceptions } from '../index'; +import { BitPayExceptionProvider } from '../Exceptions/BitPayExceptionProvider'; export class RateClient { private bitPayClient: BitPayClient; @@ -15,15 +15,17 @@ export class RateClient { * @param baseCurrency The cryptocurrency for which you want to fetch the fiat-equivalent rate. * @param currency The fiat currency for which you want to fetch the baseCurrency rate * @returns Rate A Rate object populated with the currency rate for the requested baseCurrency. - * @throws RateQueryException + * @throws BitPayGenericException BitPayGenericException class + * @throws BitPayApiException BitPayApiException class */ public async getRate(baseCurrency: string, currency: string): Promise { const uri = currency ? 'rates/' + baseCurrency + '/' + currency : '/' + baseCurrency; + const result = await this.bitPayClient.get(uri, null, false); + try { - const result = await this.bitPayClient.get(uri, null, false); return JSON.parse(result); } catch (e) { - throw new Exceptions.RateQuery(e); + BitPayExceptionProvider.throwDeserializeResourceException('Rate', e.message); } } @@ -32,16 +34,18 @@ export class RateClient { * * @param currency * @returns Rates A Rates object populated with the currency rates for the requested baseCurrency. - * @throws RateQueryException + * @throws BitPayGenericException BitPayGenericException class + * @throws BitPayApiException BitPayApiException class */ public async getRates(currency: string = null): Promise { const uri = currency ? 'rates/' + currency : 'rates'; + const result = await this.bitPayClient.get(uri, null, false); + try { - const result = await this.bitPayClient.get(uri, null, false); return new Rates(result); } catch (e) { - throw new Exceptions.RateQuery(e); + BitPayExceptionProvider.throwDeserializeResourceException('Rate', e.message); } } } diff --git a/src/Client/RefundClient.ts b/src/Client/RefundClient.ts index e21ecd2..c952953 100644 --- a/src/Client/RefundClient.ts +++ b/src/Client/RefundClient.ts @@ -1,10 +1,11 @@ import { BitPayClient } from './BitPayClient'; import { TokenContainer } from '../TokenContainer'; import { GuidGenerator } from '../util/GuidGenerator'; -import { BitPayExceptions as Exceptions, Facade } from '../index'; +import { Facade } from '../index'; import { RefundInterface } from '../Model/Invoice/Refund'; import { ParamsRemover } from '../util/ParamsRemover'; import { BitPayResponseParser } from '../util/BitPayResponseParser'; +import { BitPayExceptionProvider } from '../Exceptions/BitPayExceptionProvider'; export class RefundClient { private bitPayClient: BitPayClient; @@ -38,14 +39,12 @@ export class RefundClient { ParamsRemover.removeNullValuesFromObject(params); + const result = await this.bitPayClient.post('refunds', params, true); + try { - const result = await this.bitPayClient.post('refunds', params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.RefundCreation( - 'failed to deserialize BitPay server response (Refund) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Refund', e.message); } } @@ -54,33 +53,36 @@ export class RefundClient { * * @param refundId The BitPay refund ID. * @returns Refund BitPay Refund object with the associated Refund object. - * @throws RefundQueryException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async get(refundId: string): Promise { const params = { token: this.tokenContainer.getToken(Facade.Merchant) }; + const result = await this.bitPayClient.get('refunds/' + refundId, params, true); try { - const result = await this.bitPayClient.get('refunds/' + refundId, params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.RefundQuery( - 'failed to deserialize BitPay server response (Refund) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Refund', e.message); } } + /** + * Retrieve a previously made refund request on a BitPay invoice by Guid. + * + * @param guid The BitPay GUID. + * @returns Refund BitPay Refund object with the associated Refund object. + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class + */ public async getByGuid(guid: string): Promise { const params = { token: this.tokenContainer.getToken(Facade.Merchant) }; + const result = await this.bitPayClient.get('refunds/guid/' + guid, params, true); try { - const result = await this.bitPayClient.get('refunds/guid/' + guid, params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.RefundQuery( - 'failed to deserialize BitPay server response (Refund) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Refund', e.message); } } @@ -89,22 +91,20 @@ export class RefundClient { * * @param invoiceId The BitPay refund Guid. * @returns Refund BitPay Refund object with the associated Refund object. - * @throws RefundQueryException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async getRefunds(invoiceId: string): Promise { const params = { token: this.tokenContainer.getToken(Facade.Merchant), invoiceId: invoiceId }; + const result = await this.bitPayClient.get('refunds', params, true); try { - const result = await this.bitPayClient.get('refunds', params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.RefundQuery( - 'failed to deserialize BitPay server response (Refund) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Refund', e.message); } } @@ -113,19 +113,17 @@ export class RefundClient { * * @param refundId A BitPay refund ID. * @returns boolean An updated Refund Object - * @throws RefundException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async sendRefundNotification(refundId: string): Promise { const params = { token: this.tokenContainer.getToken(Facade.Merchant) }; + const result = await this.bitPayClient.post('refunds/' + refundId + '/notifications', params, true); try { - const result = await this.bitPayClient.post('refunds/' + refundId + '/notifications', params, true); return BitPayResponseParser.jsonToBoolean(result); } catch (e) { - throw new Exceptions.RefundGeneric( - 'failed to deserialize BitPay server response (Refund) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Refund', e.message); } } @@ -135,22 +133,20 @@ export class RefundClient { * @param refundId BitPay refund ID. * @param status The new status for the refund to be updated. * @returns Refund A BitPay generated Refund object. - * @throws RefundException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async update(refundId: string, status: string): Promise { const params = { token: this.tokenContainer.getToken(Facade.Merchant), status: status }; + const result = await this.bitPayClient.put('refunds/' + refundId, params, true); try { - const result = await this.bitPayClient.put('refunds/' + refundId, params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.RefundGeneric( - 'failed to deserialize BitPay server response (Refund) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Refund', e.message); } } @@ -160,22 +156,20 @@ export class RefundClient { * @param guid BitPay refund Guid. * @param status The new status for the refund to be updated. * @returns Refund A BitPay generated Refund object. - * @throws RefundException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async updateByGuid(guid: string, status: string): Promise { const params = { token: this.tokenContainer.getToken(Facade.Merchant), status: status }; + const result = await this.bitPayClient.put('refunds/guid/' + guid, params, true); try { - const result = await this.bitPayClient.put('refunds/guid/' + guid, params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.RefundGeneric( - 'failed to deserialize BitPay server response (Refund) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Refund', e.message); } } @@ -184,19 +178,17 @@ export class RefundClient { * * @param refundId The refund Id for the refund to be canceled. * @returns Cancelled refund Object. - * @throws RefundCreationException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async cancel(refundId: string): Promise { const params = { token: this.tokenContainer.getToken(Facade.Merchant) }; + const result = await this.bitPayClient.delete('refunds/' + refundId, params, true); try { - const result = await this.bitPayClient.delete('refunds/' + refundId, params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.RefundCancellation( - 'failed to deserialize BitPay server response (Refund) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Refund', e.message); } } @@ -205,19 +197,17 @@ export class RefundClient { * * @param guid The refund Guid for the refund to be canceled. * @returns Cancelled refund Object. - * @throws RefundCreationException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async cancelByGuid(guid: string): Promise { const params = { token: this.tokenContainer.getToken(Facade.Merchant) }; + const result = await this.bitPayClient.delete('refunds/guid/' + guid, params, true); try { - const result = await this.bitPayClient.delete('refunds/guid/' + guid, params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.RefundCancellation( - 'failed to deserialize BitPay server response (Refund) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Refund', e.message); } } } diff --git a/src/Client/SettlementClient.ts b/src/Client/SettlementClient.ts index c6054b7..3b6d4fc 100644 --- a/src/Client/SettlementClient.ts +++ b/src/Client/SettlementClient.ts @@ -1,7 +1,8 @@ import { BitPayClient } from './BitPayClient'; import { TokenContainer } from '../TokenContainer'; import { SettlementInterface } from '../Model/Settlement/Settlement'; -import { BitPayExceptions as Exceptions, Facade } from '../index'; +import { Facade } from '../index'; +import { BitPayExceptionProvider } from '../Exceptions/BitPayExceptionProvider'; export class SettlementClient { private bitPayClient: BitPayClient; @@ -17,7 +18,8 @@ export class SettlementClient { * * @param settlementId Settlement Id * @returns Settlement - * @throws SettlementQueryException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async get(settlementId: string): Promise { const params = { token: this.tokenContainer.getToken(Facade.Merchant) }; @@ -26,10 +28,7 @@ export class SettlementClient { const result = await this.bitPayClient.get('settlements/' + settlementId, params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.SettlementQuery( - 'failed to deserialize BitPay server response (Settlement) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Settlement', e.message); } } @@ -38,19 +37,18 @@ export class SettlementClient { * * @param params * @returns Settlement[] - * @throws SettlementQueryException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async getSettlements(params: object): Promise { params['token'] = this.tokenContainer.getToken(Facade.Merchant); + const result = await this.bitPayClient.get('settlements', params, true); + try { - const result = await this.bitPayClient.get('settlements', params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.SettlementQuery( - 'failed to deserialize BitPay server response (Settlement) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Settlement', e.message); } } @@ -60,19 +58,18 @@ export class SettlementClient { * @param settlementId * @param token * @returns Settlement - * @throws SettlementQueryException + * @throws BitPayApiException BitPayApiException class + * @throws BitPayGenericException BitPayGenericException class */ public async getReconciliationReport(settlementId: string, token: string): Promise { const params = { token: token }; + const result = await this.bitPayClient.get('settlements/' + settlementId + '/reconciliationReport', params, true); + try { - const result = await this.bitPayClient.get('settlements/' + settlementId + '/reconciliationReport', params, true); return JSON.parse(result); } catch (e) { - throw new Exceptions.SettlementQuery( - 'failed to deserialize BitPay server response (Settlement) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Settlement', e.message); } } } diff --git a/src/Client/WalletClient.ts b/src/Client/WalletClient.ts index 86ea604..601fd7f 100644 --- a/src/Client/WalletClient.ts +++ b/src/Client/WalletClient.ts @@ -1,6 +1,6 @@ import { BitPayClient } from './BitPayClient'; -import { BitPayExceptions as Exceptions } from '../index'; import { WalletInterface } from '../Model/Wallet/Wallet'; +import { BitPayExceptionProvider } from '../Exceptions/BitPayExceptionProvider'; export class WalletClient { private bitPayClient: BitPayClient; @@ -16,14 +16,12 @@ export class WalletClient { * @throws WalletQueryException */ public async getSupportedWallets(): Promise { + const result = await this.bitPayClient.get('supportedwallets', null, false); + try { - const result = await this.bitPayClient.get('supportedwallets', null, false); return JSON.parse(result); } catch (e) { - throw new Exceptions.WalletQuery( - 'failed to deserialize BitPay server response (Wallet) : ' + e.message, - e.apiCode - ); + BitPayExceptionProvider.throwDeserializeResourceException('Wallet', e.message); } } } diff --git a/src/Client/index.ts b/src/Client/index.ts new file mode 100644 index 0000000..6ec4052 --- /dev/null +++ b/src/Client/index.ts @@ -0,0 +1,27 @@ +import { BillClient } from './BillClient'; +import { BitPayClient } from './BitPayClient'; +import { CurrencyClient } from './CurrencyClient'; +import { InvoiceClient } from './InvoiceClient'; +import { LedgerClient } from './LedgerClient'; +import { PayoutClient } from './PayoutClient'; +import { PayoutGroupClient } from './PayoutGroupClient'; +import { PayoutRecipientClient } from './PayoutRecipientClient'; +import { RateClient } from './RateClient'; +import { RefundClient } from './RefundClient'; +import { SettlementClient } from './SettlementClient'; +import { WalletClient } from './WalletClient'; + +export { + BillClient, + BitPayClient, + CurrencyClient, + InvoiceClient, + LedgerClient, + PayoutClient, + PayoutGroupClient, + PayoutRecipientClient, + RateClient, + RefundClient, + SettlementClient, + WalletClient +}; diff --git a/src/Exceptions/BillCreationException.ts b/src/Exceptions/BillCreationException.ts deleted file mode 100644 index 508a36c..0000000 --- a/src/Exceptions/BillCreationException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import BillException from './BillException'; - -export class BillCreationException implements BillException { - public readonly message: string = 'Failed to create bill'; - public readonly name: string = 'BITPAY-BILL-CREATE'; - public readonly code: number = 112; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the BillCreationException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default BillCreationException; diff --git a/src/Exceptions/BillDeliveryException.ts b/src/Exceptions/BillDeliveryException.ts deleted file mode 100644 index 53c1a8b..0000000 --- a/src/Exceptions/BillDeliveryException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import BitPayException from './BitPayException'; - -export class BillDeliveryException implements BitPayException { - public readonly message: string = 'An unexpected error occurred while trying to manage the bill'; - public readonly name: string = 'BITPAY-BILL-DELIVERY'; - public readonly code: number = 115; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the BillDeliveryException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default BillDeliveryException; diff --git a/src/Exceptions/BillException.ts b/src/Exceptions/BillException.ts deleted file mode 100644 index 55e1019..0000000 --- a/src/Exceptions/BillException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import BitPayException from './BitPayException'; - -export class BillException implements BitPayException { - public readonly message: string = 'An unexpected error occurred while trying to manage the bill'; - public readonly name: string = 'BITPAY-BILL-GENERIC'; - public readonly code: number = 111; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the BillException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default BillException; diff --git a/src/Exceptions/BillQueryException.ts b/src/Exceptions/BillQueryException.ts deleted file mode 100644 index 000cb4f..0000000 --- a/src/Exceptions/BillQueryException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import BillException from './BillException'; - -export class BillQueryException implements BillException { - public readonly message: string = 'Failed to retrieve bill'; - public readonly name: string = 'BITPAY-BILL-GET'; - public readonly code: number = 113; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the BillQueryException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default BillQueryException; diff --git a/src/Exceptions/BillUpdateException.ts b/src/Exceptions/BillUpdateException.ts deleted file mode 100644 index 00b815d..0000000 --- a/src/Exceptions/BillUpdateException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import BitPayException from './BitPayException'; - -export class BillUpdateException implements BitPayException { - public readonly message: string = 'An unexpected error occurred while trying to manage the bill'; - public readonly name: string = 'BITPAY-BILL-UPDATE'; - public readonly code: number = 114; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the BillUpdateException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default BillUpdateException; diff --git a/src/Exceptions/BitPayApiException.ts b/src/Exceptions/BitPayApiException.ts new file mode 100644 index 0000000..430e754 --- /dev/null +++ b/src/Exceptions/BitPayApiException.ts @@ -0,0 +1,18 @@ +import BitPayException from './BitPayException'; + +export class BitPayApiException extends BitPayException { + public readonly name: string = 'BITPAY-EXCEPTION'; + public readonly code: string | null = 'BITPAY-EXCEPTION'; + /** + * Construct the BitPayException. + * + * @param message string [optional] The Exception message to throw. + * @param code string [optional] The Exception code to throw. + */ + public constructor(message: string = null, code: string = null) { + super(message); + this.code = code; + } +} + +export default BitPayApiException; diff --git a/src/Exceptions/BitPayException.ts b/src/Exceptions/BitPayException.ts index bf5de9a..441b602 100644 --- a/src/Exceptions/BitPayException.ts +++ b/src/Exceptions/BitPayException.ts @@ -1,23 +1,15 @@ export class BitPayException implements Error { - public readonly message: string = 'Unexpected Bitpay exeption'; - public readonly name: string = 'BITPAY-GENERIC'; - public readonly code: number = 100; + public readonly message: string | null; + public readonly name: string = 'BITPAY-EXCEPTION'; public readonly stack: string; - public readonly apiCode: string = '000000'; /** * Construct the BitPayException. * - * @param name string [optional] The Exception type to throw. * @param message string [optional] The Exception message to throw. - * @param code number [optional] The Exception code to throw. - * @param apiCode string [optional] The API Exception code to throw. */ - public constructor(name: string = null, message: string = null, code: number = null, apiCode = '000000') { + public constructor(message: string = null) { this.message = message ? message : this.message; - this.name = name ? name : this.name; - this.code = code ? code : this.code; - this.apiCode = apiCode ? apiCode : this.apiCode; } } diff --git a/src/Exceptions/BitPayExceptionProvider.ts b/src/Exceptions/BitPayExceptionProvider.ts new file mode 100644 index 0000000..770a578 --- /dev/null +++ b/src/Exceptions/BitPayExceptionProvider.ts @@ -0,0 +1,90 @@ +import { LoggerProvider } from '../Logger/LoggerProvider'; +import BitPayGenericException from './BitPayGenericException'; +import BitPayApiException from './BitPayApiException'; +import BitPayValidationException from './BitPayValidationException'; + +export class BitPayExceptionProvider { + static readonly GENERIC_API_UNMAPPED_ERROR_CODE: string = '000000'; + + public static throwGenericExceptionWithMessage(errorMessage: string | null): void { + this.logErrorMessage(errorMessage); + + throw new BitPayGenericException(errorMessage); + } + + public static throwApiExceptionWithMessage(errorMessage: string | null, code: string | null): void { + this.logErrorMessage(errorMessage); + + code = code ? code : this.GENERIC_API_UNMAPPED_ERROR_CODE; + + throw new BitPayApiException(errorMessage, code); + } + + public static throwDeserializeResourceException(resource: string | null, errorMessage: string | null): void { + let message: string; + if (resource === null) { + message = 'Failed to deserialize BitPay server response (' + errorMessage + '): ' + resource; + } else { + message = 'Failed to deserialize BitPay server response ( %s )'; + } + this.logErrorMessage(message); + + this.throwGenericExceptionWithMessage(message); + } + + public static throwDeserializeException(errorMessage: string | null): void { + const message = 'Failed to deserialize BitPay server response : ' + errorMessage; + + this.logErrorMessage(message); + } + + public static throwEncodeException(errorMessage: string | null): void { + this.logErrorMessage(errorMessage); + + const message = 'Failed to encode params : ' + errorMessage; + + this.throwGenericExceptionWithMessage(message); + } + + public static throwSerializeResourceException(resource: string, errorMessage: string | null): void { + const message = 'Failed to serialize ( ' + resource + ' ) : ' + errorMessage; + + this.logErrorMessage(message); + + this.throwGenericExceptionWithMessage(message); + } + + public static throwSerializeParamsException(errorMessage: string | null): void { + const message = 'Failed to serialize params : ' + errorMessage; + + this.logErrorMessage(message); + } + + public static throwValidationException(errorMessage: string | null): void { + this.logErrorMessage(errorMessage); + + throw new BitPayValidationException(errorMessage); + } + + public static throwMissingParameterException(): void { + const message = 'Missing required parameter'; + + this.logErrorMessage(message); + + throw new BitPayValidationException(message); + } + + public static throwInvalidCurrencyException(currencyCode: string | null): void { + const message: string = 'Currency code ' + currencyCode + ' must be a type of Model.Currency.Currency'; + + this.throwValidationException(message); + } + + private static logErrorMessage(message: string): void { + if (message === null) { + return; + } + + LoggerProvider.getLogger().logError(message); + } +} diff --git a/src/Exceptions/BitPayGenericException.ts b/src/Exceptions/BitPayGenericException.ts new file mode 100644 index 0000000..3d47e18 --- /dev/null +++ b/src/Exceptions/BitPayGenericException.ts @@ -0,0 +1,5 @@ +import BitPayException from './BitPayException'; + +export class BitPayGenericException extends BitPayException {} + +export default BitPayGenericException; diff --git a/src/Exceptions/BitPayValidationException.ts b/src/Exceptions/BitPayValidationException.ts new file mode 100644 index 0000000..1fc9bd3 --- /dev/null +++ b/src/Exceptions/BitPayValidationException.ts @@ -0,0 +1,5 @@ +import BitPayGenericException from './BitPayGenericException'; + +export class BitPayValidationException extends BitPayGenericException {} + +export default BitPayValidationException; diff --git a/src/Exceptions/InvoiceCreationException.ts b/src/Exceptions/InvoiceCreationException.ts deleted file mode 100644 index c271d8d..0000000 --- a/src/Exceptions/InvoiceCreationException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import InvoiceException from './InvoiceException'; - -export class InvoiceCreationException implements InvoiceException { - public readonly message: string = 'Failed to create invoice'; - public readonly name: string = 'BITPAY-INVOICE-CREATE'; - public readonly code: number = 102; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the InvoiceCreationException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default InvoiceCreationException; diff --git a/src/Exceptions/InvoiceException.ts b/src/Exceptions/InvoiceException.ts deleted file mode 100644 index f39961c..0000000 --- a/src/Exceptions/InvoiceException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import BitPayException from './BitPayException'; - -export class InvoiceException implements BitPayException { - public readonly message: string = 'An unexpected error occurred while trying to manage the invoice'; - public readonly name: string = 'BITPAY-INVOICE-GENERIC'; - public readonly code: number = 101; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the InvoiceException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default InvoiceException; diff --git a/src/Exceptions/InvoiceQueryException.ts b/src/Exceptions/InvoiceQueryException.ts deleted file mode 100644 index a38cd2d..0000000 --- a/src/Exceptions/InvoiceQueryException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import InvoiceException from './InvoiceException'; - -export class InvoiceQueryException implements InvoiceException { - public readonly message: string = 'Failed to retrieve invoice'; - public readonly name: string = 'BITPAY-INVOICE-GET'; - public readonly code: number = 103; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the InvoiceQueryException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default InvoiceQueryException; diff --git a/src/Exceptions/InvoiceUpdateException.ts b/src/Exceptions/InvoiceUpdateException.ts deleted file mode 100644 index c20cf2b..0000000 --- a/src/Exceptions/InvoiceUpdateException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import InvoiceException from './InvoiceException'; - -export class InvoiceUpdateException implements InvoiceException { - public readonly message: string = 'Failed to create invoice'; - public readonly name: string = 'BITPAY-INVOICE-UPDATE'; - public readonly code: number = 104; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the InvoiceUpdateException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default InvoiceUpdateException; diff --git a/src/Exceptions/LedgerException.ts b/src/Exceptions/LedgerException.ts deleted file mode 100644 index 9a64629..0000000 --- a/src/Exceptions/LedgerException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import BitPayException from './BitPayException'; - -export class LedgerException implements BitPayException { - public readonly message: string = 'An unexpected error occurred while trying to manage the ledger'; - public readonly name: string = 'BITPAY-LEDGER-GENERIC'; - public readonly code: number = 131; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the LedgerException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default LedgerException; diff --git a/src/Exceptions/LedgerQueryException.ts b/src/Exceptions/LedgerQueryException.ts deleted file mode 100644 index 270949d..0000000 --- a/src/Exceptions/LedgerQueryException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import LedgerException from './InvoiceException'; - -export class LedgerQueryException implements LedgerException { - public readonly message: string = 'Failed to retrieve ledger'; - public readonly name: string = 'BITPAY-LEDGER-GET'; - public readonly code: number = 132; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the LedgerQueryException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default LedgerQueryException; diff --git a/src/Exceptions/PayoutCancellationException.ts b/src/Exceptions/PayoutCancellationException.ts deleted file mode 100644 index 3122303..0000000 --- a/src/Exceptions/PayoutCancellationException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import PayoutException from './PayoutException'; - -export class PayoutCancellationException implements PayoutException { - public readonly message: string = 'Failed to cancel payout'; - public readonly name: string = 'BITPAY-PAYOUT-CANCEL'; - public readonly code: number = 124; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the PayoutCancellationException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default PayoutCancellationException; diff --git a/src/Exceptions/PayoutCreationException.ts b/src/Exceptions/PayoutCreationException.ts deleted file mode 100644 index 24383f1..0000000 --- a/src/Exceptions/PayoutCreationException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import PayoutException from './PayoutException'; - -export class PayoutCreationException implements PayoutException { - public readonly message: string = 'Failed to create payout'; - public readonly name: string = 'BITPAY-PAYOUT-SUBMIT'; - public readonly code: number = 122; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the PayoutCreationException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default PayoutCreationException; diff --git a/src/Exceptions/PayoutDeleteException.ts b/src/Exceptions/PayoutDeleteException.ts deleted file mode 100644 index 8b2d79b..0000000 --- a/src/Exceptions/PayoutDeleteException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import PayoutException from './PayoutException'; - -export class PayoutDeleteException implements PayoutException { - public readonly message: string = 'Failed to delete payout'; - public readonly name: string = 'BITPAY-PAYOUT-DELETE'; - public readonly code: number = 126; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the PayoutDeleteException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default PayoutDeleteException; diff --git a/src/Exceptions/PayoutException.ts b/src/Exceptions/PayoutException.ts deleted file mode 100644 index 0ce7358..0000000 --- a/src/Exceptions/PayoutException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import BitPayException from './BitPayException'; - -export class PayoutException implements BitPayException { - public readonly message: string = 'An unexpected error occurred while trying to manage the payout batch'; - public readonly name: string = 'BITPAY-PAYOUT-GENERIC'; - public readonly code: number = 121; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the PayoutException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default PayoutException; diff --git a/src/Exceptions/PayoutNotificationException.ts b/src/Exceptions/PayoutNotificationException.ts deleted file mode 100644 index 8256839..0000000 --- a/src/Exceptions/PayoutNotificationException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import PayoutException from './PayoutException'; - -export class PayoutNotificationException implements PayoutException { - public readonly message: string = 'Failed to payout notification'; - public readonly name: string = 'BITPAY-PAYOUT-NOTIFICATION'; - public readonly code: number = 127; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the PayoutNotificationException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default PayoutNotificationException; diff --git a/src/Exceptions/PayoutQueryException.ts b/src/Exceptions/PayoutQueryException.ts deleted file mode 100644 index 78b3c26..0000000 --- a/src/Exceptions/PayoutQueryException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import PayoutException from './PayoutException'; - -export class PayoutQueryException implements PayoutException { - public readonly message: string = 'Failed to retrieve payout'; - public readonly name: string = 'BITPAY-PAYOUT-GET'; - public readonly code: number = 123; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the PayoutQueryException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default PayoutQueryException; diff --git a/src/Exceptions/PayoutRecipientCancellationException.ts b/src/Exceptions/PayoutRecipientCancellationException.ts deleted file mode 100644 index 86a7f76..0000000 --- a/src/Exceptions/PayoutRecipientCancellationException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import PayoutRecipientException from './PayoutRecipientException'; - -export class PayoutRecipientCancellationException implements PayoutRecipientException { - public readonly message: string = 'Failed to cancel payout recipient'; - public readonly name: string = 'BITPAY-PAYOUT-RECIPIENT-CANCEL'; - public readonly code: number = 194; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the PayoutRecipientCancellationException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default PayoutRecipientCancellationException; diff --git a/src/Exceptions/PayoutRecipientCreationException.ts b/src/Exceptions/PayoutRecipientCreationException.ts deleted file mode 100644 index f896c83..0000000 --- a/src/Exceptions/PayoutRecipientCreationException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import PayoutRecipientException from './PayoutRecipientException'; - -export class PayoutRecipientCreationException implements PayoutRecipientException { - public readonly message: string = 'Failed to create payout recipient'; - public readonly name: string = 'BITPAY-PAYOUT-RECIPIENT-SUBMIT'; - public readonly code: number = 192; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the PayoutRecipientCreationException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default PayoutRecipientCreationException; diff --git a/src/Exceptions/PayoutRecipientException.ts b/src/Exceptions/PayoutRecipientException.ts deleted file mode 100644 index 8793282..0000000 --- a/src/Exceptions/PayoutRecipientException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import BitPayException from './BitPayException'; - -export class PayoutRecipientException implements BitPayException { - public readonly message: string = 'An unexpected error occurred while trying to manage the payout recipient'; - public readonly name: string = 'BITPAY-PAYOUT-RECIPIENT-GENERIC'; - public readonly code: number = 191; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the PayoutRecipientException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default PayoutRecipientException; diff --git a/src/Exceptions/PayoutRecipientNotificationException.ts b/src/Exceptions/PayoutRecipientNotificationException.ts deleted file mode 100644 index 5f4d28a..0000000 --- a/src/Exceptions/PayoutRecipientNotificationException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import PayoutRecipientException from './PayoutRecipientException'; - -export class PayoutRecipientNotificationException implements PayoutRecipientException { - public readonly message: string = 'Failed to payout recipient notification'; - public readonly name: string = 'BITPAY-PAYOUT-RECIPIENT-NOTIFICATION'; - public readonly code: number = 196; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the PayoutRecipientNotificationException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default PayoutRecipientNotificationException; diff --git a/src/Exceptions/PayoutRecipientQueryException.ts b/src/Exceptions/PayoutRecipientQueryException.ts deleted file mode 100644 index 5a6db30..0000000 --- a/src/Exceptions/PayoutRecipientQueryException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import PayoutRecipientException from './PayoutRecipientException'; - -export class PayoutRecipientQueryException implements PayoutRecipientException { - public readonly message: string = 'Failed to retrieve payout recipient'; - public readonly name: string = 'BITPAY-PAYOUT-RECIPIENT-GET'; - public readonly code: number = 193; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the PayoutRecipientQueryException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default PayoutRecipientQueryException; diff --git a/src/Exceptions/PayoutRecipientUpdateException.ts b/src/Exceptions/PayoutRecipientUpdateException.ts deleted file mode 100644 index 625648d..0000000 --- a/src/Exceptions/PayoutRecipientUpdateException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import PayoutRecipientException from './PayoutRecipientException'; - -export class PayoutRecipientUpdateException implements PayoutRecipientException { - public readonly message: string = 'Failed to update payout recipient'; - public readonly name: string = 'BITPAY-PAYOUT-RECIPIENT-UPDATE'; - public readonly code: number = 195; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the PayoutRecipientUpdateException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default PayoutRecipientUpdateException; diff --git a/src/Exceptions/PayoutUpdateException.ts b/src/Exceptions/PayoutUpdateException.ts deleted file mode 100644 index a307ba6..0000000 --- a/src/Exceptions/PayoutUpdateException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import PayoutException from './PayoutException'; - -export class PayoutUpdateException implements PayoutException { - public readonly message: string = 'An unexpected error occurred while trying to manage the payout'; - public readonly name: string = 'BITPAY-PAYOUT-UPDATE'; - public readonly code: number = 125; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the PayoutUpdateException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default PayoutUpdateException; diff --git a/src/Exceptions/RateException.ts b/src/Exceptions/RateException.ts deleted file mode 100644 index 50cf200..0000000 --- a/src/Exceptions/RateException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import BitPayException from './BitPayException'; - -export class RateException implements BitPayException { - public readonly message: string = 'An unexpected error occurred while trying to manage the rates'; - public readonly name: string = 'BITPAY-RATES-GENERIC'; - public readonly code: number = 141; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the RateException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default RateException; diff --git a/src/Exceptions/RateQueryException.ts b/src/Exceptions/RateQueryException.ts deleted file mode 100644 index 8d1bb71..0000000 --- a/src/Exceptions/RateQueryException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import RateException from './RateException'; - -export class RateQueryException implements RateException { - public readonly message: string = 'Failed to retrieve rates'; - public readonly name: string = 'BITPAY-RATES-GET'; - public readonly code: number = 142; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the RateQueryException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default RateQueryException; diff --git a/src/Exceptions/RefundCancellationException.ts b/src/Exceptions/RefundCancellationException.ts deleted file mode 100644 index a799061..0000000 --- a/src/Exceptions/RefundCancellationException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import RefundException from './RefundException'; - -export class RefundCancellationException implements RefundException { - public readonly message: string = 'Failed to create refund'; - public readonly name: string = 'BITPAY-REFUND-CREATE'; - public readonly code: number = 164; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the RefundCreationException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default RefundCancellationException; diff --git a/src/Exceptions/RefundCreationException.ts b/src/Exceptions/RefundCreationException.ts deleted file mode 100644 index 41399f8..0000000 --- a/src/Exceptions/RefundCreationException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import RefundException from './RefundException'; - -export class RefundCreationException implements RefundException { - public readonly message: string = 'Failed to create refund'; - public readonly name: string = 'BITPAY-REFUND-CREATE'; - public readonly code: number = 162; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the RefundCreationException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default RefundCreationException; diff --git a/src/Exceptions/RefundException.ts b/src/Exceptions/RefundException.ts deleted file mode 100644 index 271a0b2..0000000 --- a/src/Exceptions/RefundException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import BitPayException from './BitPayException'; - -export class RefundException implements BitPayException { - public readonly message: string = 'An unexpected error occurred while trying to manage the refund'; - public readonly name: string = 'BITPAY-REFUND-GENERIC'; - public readonly code: number = 161; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the RefundException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default RefundException; diff --git a/src/Exceptions/RefundQueryException.ts b/src/Exceptions/RefundQueryException.ts deleted file mode 100644 index 6b00184..0000000 --- a/src/Exceptions/RefundQueryException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import RefundException from './RefundException'; - -export class RefundQueryException implements RefundException { - public readonly message: string = 'Failed to retrieve refund'; - public readonly name: string = 'BITPAY-REFUND-GET'; - public readonly code: number = 163; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the RefundQueryException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default RefundQueryException; diff --git a/src/Exceptions/SettlementException.ts b/src/Exceptions/SettlementException.ts deleted file mode 100644 index ab22314..0000000 --- a/src/Exceptions/SettlementException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import BitPayException from './BitPayException'; - -export class SettlementException implements BitPayException { - public readonly message: string = 'An unexpected error occurred while trying to manage the settlements'; - public readonly name: string = 'BITPAY-SETTLEMENTS-GENERIC'; - public readonly code: number = 151; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the SettlementException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default SettlementException; diff --git a/src/Exceptions/SettlementQueryException.ts b/src/Exceptions/SettlementQueryException.ts deleted file mode 100644 index 25cd127..0000000 --- a/src/Exceptions/SettlementQueryException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import SettlementException from './SettlementException'; - -export class SettlementQueryException implements SettlementException { - public readonly message: string = 'Failed to retrieve settlements'; - public readonly name: string = 'BITPAY-SETTLEMENTS-GET'; - public readonly code: number = 152; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the SettlementQueryException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default SettlementQueryException; diff --git a/src/Exceptions/SubscriptionCreationException.ts b/src/Exceptions/SubscriptionCreationException.ts deleted file mode 100644 index 74c2ae4..0000000 --- a/src/Exceptions/SubscriptionCreationException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import SubscriptionException from './SubscriptionException'; - -export class SubscriptionCreationException implements SubscriptionException { - public readonly message: string = 'Failed to create subscription'; - public readonly name: string = 'BITPAY-SUBSCRIPTION-CREATE'; - public readonly code: number = 172; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the SubscriptionCreationException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default SubscriptionCreationException; diff --git a/src/Exceptions/SubscriptionException.ts b/src/Exceptions/SubscriptionException.ts deleted file mode 100644 index 704afea..0000000 --- a/src/Exceptions/SubscriptionException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import BitPayException from './BitPayException'; - -export class SubscriptionException implements BitPayException { - public readonly message: string = 'An unexpected error occurred while trying to manage the subscription'; - public readonly name: string = 'BITPAY-SUBSCRIPTION-GENERIC'; - public readonly code: number = 171; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the SubscriptionException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default SubscriptionException; diff --git a/src/Exceptions/SubscriptionQueryException.ts b/src/Exceptions/SubscriptionQueryException.ts deleted file mode 100644 index 11a74af..0000000 --- a/src/Exceptions/SubscriptionQueryException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import SubscriptionException from './SubscriptionException'; - -export class SubscriptionQueryException implements SubscriptionException { - public readonly message: string = 'Failed to retrieve subscription'; - public readonly name: string = 'BITPAY-SUBSCRIPTION-GET'; - public readonly code: number = 173; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the SubscriptionQueryException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default SubscriptionQueryException; diff --git a/src/Exceptions/SubscriptionUpdateException.ts b/src/Exceptions/SubscriptionUpdateException.ts deleted file mode 100644 index 02a3246..0000000 --- a/src/Exceptions/SubscriptionUpdateException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import SubscriptionException from './SubscriptionException'; - -export class SubscriptionUpdateException implements SubscriptionException { - public readonly message: string = 'An unexpected error occurred while trying to manage the subscription'; - public readonly name: string = 'BITPAY-SUBSCRIPTION-UPDATE'; - public readonly code: number = 174; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the SubscriptionUpdateException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default SubscriptionUpdateException; diff --git a/src/Exceptions/WalletQueryException.ts b/src/Exceptions/WalletQueryException.ts deleted file mode 100644 index 5bb2f35..0000000 --- a/src/Exceptions/WalletQueryException.ts +++ /dev/null @@ -1,22 +0,0 @@ -import SubscriptionException from './SubscriptionException'; - -export class WalletQueryException implements SubscriptionException { - public readonly message: string = 'Failed to retrieve subscription'; - public readonly name: string = 'BITPAY-SUBSCRIPTION-GET'; - public readonly code: number = 173; - public readonly stack: string; - public readonly apiCode: string = '000000'; - - /** - * Construct the SubscriptionQueryException. - * - * @param message string [optional] The Exception message to throw. - * @param apiCode string [optional] The API Exception code to throw. - */ - public constructor(message: string, apiCode = '000000') { - this.message = message ? message : this.message; - this.apiCode = apiCode ? apiCode : this.apiCode; - } -} - -export default WalletQueryException; diff --git a/src/Exceptions/index.ts b/src/Exceptions/index.ts index 91cd50a..3a96c06 100644 --- a/src/Exceptions/index.ts +++ b/src/Exceptions/index.ts @@ -13,82 +13,8 @@ * See the LICENSE file for more info. */ -import { BitPayException as Generic } from './BitPayException'; -import { InvoiceException as InvoiceGeneric } from './InvoiceException'; -import { InvoiceCreationException as InvoiceCreation } from './InvoiceCreationException'; -import { InvoiceQueryException as InvoiceQuery } from './InvoiceQueryException'; -import { InvoiceUpdateException as InvoiceUpdate } from './InvoiceUpdateException'; -import { RateException as RateGeneric } from './RateException'; -import { RateQueryException as RateQuery } from './RateQueryException'; -import { RefundException as RefundGeneric } from './RefundException'; -import { RefundCreationException as RefundCreation } from './RefundCreationException'; -import { RefundQueryException as RefundQuery } from './RefundQueryException'; -import { RefundCancellationException as RefundCancellation } from './RefundCancellationException'; -import { BillException as BillGeneric } from './BillException'; -import { BillCreationException as BillCreation } from './BillCreationException'; -import { BillQueryException as BillQuery } from './BillQueryException'; -import { BillDeliveryException as BillDelivery } from './BillDeliveryException'; -import { BillUpdateException as BillUpdate } from './BillUpdateException'; -import { LedgerException as LedgerGeneric } from './LedgerException'; -import { LedgerQueryException as LedgerQuery } from './LedgerQueryException'; -import { PayoutException as PayoutGeneric } from './PayoutException'; -import { PayoutCreationException as PayoutCreation } from './PayoutCreationException'; -import { PayoutQueryException as PayoutQuery } from './PayoutQueryException'; -import { PayoutCancellationException as PayoutCancellation } from './PayoutCancellationException'; -import { PayoutUpdateException as PayoutUpdate } from './PayoutUpdateException'; -import { PayoutDeleteException as PayoutDelete } from './PayoutDeleteException'; -import { PayoutNotificationException as PayoutNotification } from './PayoutNotificationException'; -import { PayoutRecipientException as PayoutRecipientGeneric } from './PayoutRecipientException'; -import { PayoutRecipientCreationException as PayoutRecipientCreation } from './PayoutRecipientCreationException'; -import { PayoutRecipientQueryException as PayoutRecipientQuery } from './PayoutRecipientQueryException'; -import { PayoutRecipientCancellationException as PayoutRecipientCancellation } from './PayoutRecipientCancellationException'; -import { PayoutRecipientUpdateException as PayoutRecipientUpdate } from './PayoutRecipientUpdateException'; -import { PayoutRecipientNotificationException as PayoutRecipientNotification } from './PayoutRecipientNotificationException'; -import { SettlementException as SettlementGeneric } from './SettlementException'; -import { SettlementQueryException as SettlementQuery } from './SettlementQueryException'; -import { SubscriptionException as SubscriptionGeneric } from './SubscriptionException'; -import { SubscriptionCreationException as SubscriptionCreation } from './SubscriptionCreationException'; -import { SubscriptionQueryException as SubscriptionQuery } from './SubscriptionQueryException'; -import { SubscriptionUpdateException as SubscriptionUpdate } from './SubscriptionUpdateException'; -import { WalletQueryException as WalletQuery } from './WalletQueryException'; +import { BitPayGenericException as Generic } from './BitPayGenericException'; +import { BitPayApiException as Api } from './BitPayApiException'; +import { BitPayValidationException as Validation } from './BitPayValidationException'; -export { - Generic, - InvoiceGeneric, - InvoiceCreation, - InvoiceQuery, - InvoiceUpdate, - RateGeneric, - RateQuery, - RefundGeneric, - RefundCreation, - RefundQuery, - RefundCancellation, - BillGeneric, - BillCreation, - BillQuery, - BillDelivery, - BillUpdate, - LedgerGeneric, - LedgerQuery, - PayoutGeneric, - PayoutCreation, - PayoutQuery, - PayoutCancellation, - PayoutUpdate, - PayoutDelete, - PayoutNotification, - PayoutRecipientGeneric, - PayoutRecipientCreation, - PayoutRecipientQuery, - PayoutRecipientCancellation, - PayoutRecipientUpdate, - PayoutRecipientNotification, - SettlementGeneric, - SettlementQuery, - SubscriptionGeneric, - SubscriptionCreation, - SubscriptionQuery, - SubscriptionUpdate, - WalletQuery -}; +export { Generic, Api, Validation }; diff --git a/src/Logger/BitPayLogger.ts b/src/Logger/BitPayLogger.ts new file mode 100644 index 0000000..39e8dba --- /dev/null +++ b/src/Logger/BitPayLogger.ts @@ -0,0 +1,7 @@ +export interface BitPayLogger { + logRequest(method: string, endpoint: string, json: string); + + logResponse(method: string, endpoint: string, json: string); + + logError(message: string); +} diff --git a/src/Logger/EmptyLogger.ts b/src/Logger/EmptyLogger.ts new file mode 100644 index 0000000..6639d97 --- /dev/null +++ b/src/Logger/EmptyLogger.ts @@ -0,0 +1,11 @@ +import { BitPayLogger } from './BitPayLogger'; + +/* eslint @typescript-eslint/no-unused-vars: "off" */ + +export class EmptyLogger implements BitPayLogger { + logError(message: string) {} + + logRequest(method: string, endpoint: string, json: string) {} + + logResponse(method: string, endpoint: string, json: string) {} +} diff --git a/src/Logger/LoggerProvider.ts b/src/Logger/LoggerProvider.ts new file mode 100644 index 0000000..4e4326a --- /dev/null +++ b/src/Logger/LoggerProvider.ts @@ -0,0 +1,24 @@ +import { BitPayLogger } from './BitPayLogger'; +import { EmptyLogger } from './EmptyLogger'; + +export class LoggerProvider { + private static logger: BitPayLogger | null = null; + + private constructor() {} + + public static getLogger(): BitPayLogger { + if (LoggerProvider.logger === null) { + LoggerProvider.logger = new EmptyLogger(); + } + + return LoggerProvider.logger; + } + + /** + * Set BitPayLogger. + * @param bitPayLogger BitPayLogger + */ + public static setLogger(bitPayLogger: BitPayLogger) { + LoggerProvider.logger = bitPayLogger; + } +} diff --git a/src/Logger/WinstonLoggerExample.ts b/src/Logger/WinstonLoggerExample.ts new file mode 100644 index 0000000..8d6c0b4 --- /dev/null +++ b/src/Logger/WinstonLoggerExample.ts @@ -0,0 +1,28 @@ +// import { BitPayLogger } from './BitPayLogger'; +// import * as winston from 'winston'; +// +// export class WinstonLoggerExample implements BitPayLogger { +// private logger: winston.Logger; +// +// constructor() { +// this.logger = winston.createLogger({ +// level: 'info', +// transports: [ +// new winston.transports.File({ filename: 'error.log', level: 'error' }), +// new winston.transports.File({ filename: 'logs.log' }) +// ] +// }); +// } +// +// logRequest(method: string, endpoint: string, json: string) { +// this.logger.info('Request method:' + method + ' Endpoint: ' + endpoint + ' Json: ' + json); +// } +// +// logResponse(method: string, endpoint: string, json: string) { +// this.logger.info('Response method: ' + method + ' Endpoint: ' + endpoint + ' Json: ' + json); +// } +// +// logError(message: string) { +// this.logger.error(message); +// } +// } diff --git a/src/Model/Bill/Bill.ts b/src/Model/Bill/Bill.ts index e79d44e..37e64b1 100644 --- a/src/Model/Bill/Bill.ts +++ b/src/Model/Bill/Bill.ts @@ -1,6 +1,6 @@ import { Currency } from '../../Currency'; -import BitPayException from '../../Exceptions/BitPayException'; import { Item } from './Item'; +import { BitPayExceptionProvider } from '../../Exceptions/BitPayExceptionProvider'; export interface BillInterface { currency: string | null; @@ -64,11 +64,10 @@ export class Bill implements BillInterface { this.items = items; } - setCurrency(_currency: string) { - if (!Currency.isValid(_currency)) - throw new BitPayException(null, 'Error: currency code must be a type of Model.Currency', null); + setCurrency(currency: string) { + if (!Currency.isValid(currency)) BitPayExceptionProvider.throwInvalidCurrencyException(currency); - this.currency = _currency; + this.currency = currency; } } diff --git a/src/Model/Invoice/Invoice.ts b/src/Model/Invoice/Invoice.ts index c725d47..aae7370 100644 --- a/src/Model/Invoice/Invoice.ts +++ b/src/Model/Invoice/Invoice.ts @@ -1,5 +1,4 @@ import { Currency } from '../../Currency'; -import BitPayException from '../../Exceptions/BitPayException'; import { Buyer } from './Buyer'; import { InvoiceBuyerProvidedInfo } from './InvoiceBuyerProvidedInfo'; import { InvoiceTransaction } from './InvoiceTransaction'; @@ -8,6 +7,7 @@ import { Shopper } from './Shopper'; import { RefundInfo } from './RefundInfo'; import { SupportedTransactionCurrencies } from './SupportedTransactionCurrencies'; import { InvoiceUniversalCodes } from './InvoiceUniversalCodes'; +import { BitPayExceptionProvider } from '../../Exceptions/BitPayExceptionProvider'; export interface InvoiceInterface { // API fields @@ -168,10 +168,14 @@ export class Invoice implements InvoiceInterface { this.setCurrency(currency); } - setCurrency(_currency: string) { - if (!Currency.isValid(_currency)) - throw new BitPayException(null, 'Error: currency code must be a type of Model.Currency', null); + /** + * Set currency for invoice. + * @param currency string + * @throws BitPayGenericException BitPayGenericException class + */ + setCurrency(currency: string) { + if (!Currency.isValid(currency)) BitPayExceptionProvider.throwInvalidCurrencyException(currency); - this.currency = _currency; + this.currency = currency; } } diff --git a/src/Model/Payout/PayoutInstruction.ts b/src/Model/Payout/PayoutInstruction.ts deleted file mode 100644 index b9f41b1..0000000 --- a/src/Model/Payout/PayoutInstruction.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { PayoutInstructionTransaction } from './PayoutInstructionTransaction'; -import { PayoutInstructionBtcSummary } from './PayoutInstructionBtcSummary'; -import { RecipientReferenceMethod } from '../../index'; -import PayoutCreationException from '../../Exceptions/PayoutCreationException'; - -export interface PayoutInstructionInterface { - amount: number | null; - email: string | null; - recipientId: string | null; - shopperId: string | null; - label: string | null; - id: string | null; - address: string | null; - - btc: PayoutInstructionBtcSummary; - transactions: PayoutInstructionTransaction[]; - status: string | null; -} - -export class PayoutInstruction implements PayoutInstructionInterface { - amount: number | null; - btc: PayoutInstructionBtcSummary; - email: string | null; - id: string | null; - label: string | null; - recipientId: string | null; - shopperId: string | null; - status: string | null; - transactions: PayoutInstructionTransaction[]; - address: string | null; - - /** - * Constructor, create a PayoutInstruction object. - * - * @param amount float amount (in currency of batch). - * @param method int Method used to target the recipient. - * @param methodValue string value for the choosen target method. - * @throws PayoutCreationException BitPayException class - */ - public constructor(amount: number, method: number, methodValue: string) { - this.amount = amount; - switch (method) { - case RecipientReferenceMethod.EMAIL: - this.email = methodValue; - break; - case RecipientReferenceMethod.RECIPIENT_ID: - this.recipientId = methodValue; - break; - case RecipientReferenceMethod.SHOPPER_ID: - this.shopperId = methodValue; - break; - default: - throw new PayoutCreationException('method code must be a type of RecipientReferenceMethod'); - } - } -} diff --git a/src/Model/Payout/PayoutInstructionBtcSummary.ts b/src/Model/Payout/PayoutInstructionBtcSummary.ts deleted file mode 100644 index 59028a2..0000000 --- a/src/Model/Payout/PayoutInstructionBtcSummary.ts +++ /dev/null @@ -1,14 +0,0 @@ -export interface PayoutInstructionBtcSummaryInterface { - paid: number | null; - unpaid: number | null; -} - -export class PayoutInstructionBtcSummary implements PayoutInstructionBtcSummaryInterface { - paid: number | null; - unpaid: number | null; - - public constructor(paid: number, unpaid: number) { - this.paid = paid; - this.unpaid = unpaid; - } -} diff --git a/src/Model/Payout/PayoutInstructionTransaction.ts b/src/Model/Payout/PayoutInstructionTransaction.ts deleted file mode 100644 index 3b2888a..0000000 --- a/src/Model/Payout/PayoutInstructionTransaction.ts +++ /dev/null @@ -1,13 +0,0 @@ -export interface PayoutInstructionTransactionInterface { - txid: string | null; - amount: number | null; - date: number | null; -} - -export class PayoutInstructionTransaction implements PayoutInstructionTransactionInterface { - txid: string | null; - amount: number | null; - date: number | null; - - public constructor() {} -} diff --git a/src/Model/Rates/Rates.ts b/src/Model/Rates/Rates.ts index 58c552c..5595706 100644 --- a/src/Model/Rates/Rates.ts +++ b/src/Model/Rates/Rates.ts @@ -1,5 +1,5 @@ -import RateQueryException from '../../Exceptions/RateQueryException'; import { RateClient } from '../../Client/RateClient'; +import { BitPayExceptionProvider } from '../../Exceptions/BitPayExceptionProvider'; interface RateInterface { Name: string; @@ -13,7 +13,7 @@ class Rates { private rates: RateInterface[]; public constructor(rates: RateInterface[]) { - this.rates = this.castRatesObj(rates); + this.rates = Rates.castRatesObj(rates); } public getRates() { @@ -33,15 +33,11 @@ class Rates { } public async update(rateClient: RateClient) { - try { - const rates = await rateClient.getRates(); - this.rates = rates.getRates(); - } catch (e) { - throw new RateQueryException(e); - } + const rates = await rateClient.getRates(); + this.rates = rates.getRates(); } - private castRatesObj(ratesObj: RateInterface[] | string): RateInterface[] { + private static castRatesObj(ratesObj: RateInterface[] | string): RateInterface[] { try { if (typeof ratesObj === 'string' || ratesObj instanceof String) { ratesObj = JSON.parse(ratesObj.toString()); @@ -49,7 +45,7 @@ class Rates { return ratesObj; } catch (e) { - throw new RateQueryException(e); + BitPayExceptionProvider.throwGenericExceptionWithMessage(e.message); } } } diff --git a/src/Model/index.ts b/src/Model/index.ts index f47b345..979df13 100644 --- a/src/Model/index.ts +++ b/src/Model/index.ts @@ -23,7 +23,6 @@ import { PayoutRecipient, PayoutRecipientInterface } from './Payout/PayoutRecipi import { PayoutRecipients, PayoutRecipientsInterface } from './Payout/PayoutRecipients'; import { Payout, PayoutInterface } from './Payout/Payout'; import { PayoutGroupInterface } from './Payout/PayoutGroup'; -import { PayoutInstruction, PayoutInstructionInterface } from './Payout/PayoutInstruction'; import { BillData } from './Subscription/BillData'; import { Item as SubscriptionItem } from './Subscription/Item'; @@ -44,8 +43,6 @@ export { Payout, PayoutInterface, PayoutGroupInterface, - PayoutInstruction, - PayoutInstructionInterface, BillData, SubscriptionItem }; diff --git a/src/TokenContainer.ts b/src/TokenContainer.ts index 6bf426a..3e45c59 100644 --- a/src/TokenContainer.ts +++ b/src/TokenContainer.ts @@ -1,5 +1,5 @@ -import BitPayException from './Exceptions/BitPayException'; import { Facade } from './Facade'; +import { BitPayExceptionProvider } from './Exceptions/BitPayExceptionProvider'; export class TokenContainer { private readonly data: Map; @@ -17,10 +17,11 @@ export class TokenContainer { * * @param key * @returns string + * @throws BitPayGenericException BitPayGenericException class */ public getToken(key: string): string { if (!this.data.has(key)) { - throw new BitPayException(null, 'There is no token for the specified key : ' + key); + BitPayExceptionProvider.throwGenericExceptionWithMessage('There is no token for the specified key : ' + key); } return this.data.get(key); diff --git a/src/util/BitPayResponseParser.ts b/src/util/BitPayResponseParser.ts index c22d737..180c88c 100644 --- a/src/util/BitPayResponseParser.ts +++ b/src/util/BitPayResponseParser.ts @@ -1,44 +1,48 @@ -import BitPayException from '../Exceptions/BitPayException'; +import { BitPayExceptionProvider } from '../Exceptions/BitPayExceptionProvider'; +import { BitPayApiException } from '../Exceptions/BitPayApiException'; export class BitPayResponseParser { - public async responseToJsonString(response: Response) { - try { - if (response == null) { - throw new BitPayException(null, 'Error: HTTP response is null'); - } - const responsObj = await response.json(); + public async getJsonDataFromJsonResponse(responseObj: object) { + if (responseObj === null) { + BitPayExceptionProvider.throwApiExceptionWithMessage('HTTP response is null', null); + } - if (Object.prototype.hasOwnProperty.call(responsObj, 'status')) { - if (responsObj['status'] === 'error') { - throw new BitPayException(null, 'Error: ' + responsObj['error'], null, responsObj['code']); + try { + if (Object.prototype.hasOwnProperty.call(responseObj, 'status')) { + if (responseObj['status'] === 'error') { + BitPayExceptionProvider.throwApiExceptionWithMessage( + responseObj['error'] ?? null, + responseObj['code'] ?? null + ); } - if (Object.prototype.hasOwnProperty.call(responsObj, 'data') && Object.keys(responsObj.data).length === 0) { - return JSON.stringify(responsObj); + if ( + Object.prototype.hasOwnProperty.call(responseObj, 'data') && + Object.keys(responseObj['data']).length === 0 + ) { + return JSON.stringify(responseObj); } } - if (Object.prototype.hasOwnProperty.call(responsObj, 'error')) { - throw new BitPayException(null, 'Error: ' + responsObj['error']); - } else if (Object.prototype.hasOwnProperty.call(responsObj, 'errors')) { - let message = ''; - responsObj['errors'].forEach(function (error) { - message += '\n' + error.toString(); - }); - throw new BitPayException(null, 'Errors: ' + message); + if (Object.prototype.hasOwnProperty.call(responseObj, 'error')) { + BitPayExceptionProvider.throwApiExceptionWithMessage(responseObj['error'] ?? null, responseObj['code'] ?? null); } - if (Object.prototype.hasOwnProperty.call(responsObj, 'success')) { - return JSON.stringify(responsObj['success']); + if (Object.prototype.hasOwnProperty.call(responseObj, 'success')) { + return JSON.stringify(responseObj['success']); } - if (Object.prototype.hasOwnProperty.call(responsObj, 'data')) { - return JSON.stringify(responsObj['data']); + if (Object.prototype.hasOwnProperty.call(responseObj, 'data')) { + return JSON.stringify(responseObj['data']); } - return JSON.stringify(responsObj); + return JSON.stringify(responseObj); } catch (e) { - throw new BitPayException(null, 'failed to retrieve HTTP response body : ' + e.message); + if (e instanceof BitPayApiException) { + throw e; + } + + BitPayExceptionProvider.throwApiExceptionWithMessage(e.message, null); } } diff --git a/test/clientUnit.spec.ts b/test/clientUnit.spec.ts index 58b924e..b3e2633 100644 --- a/test/clientUnit.spec.ts +++ b/test/clientUnit.spec.ts @@ -26,6 +26,7 @@ import * as updateBillRequestMock from './json/updateBillRequest.json'; import * as updateBillResponseMock from './json/updateBillResponse.json'; import * as deliverBillRequestMock from './json/deliverBillRequest.json'; import * as deliverBillResponseMock from './json/deliverBillResponse.json'; +import * as errorResponse from './json/errorResponse.json'; import * as getCurrenciesResponseMock from './json/getCurrenciesResponse.json'; import * as createInvoiceRequestMock from './json/createInvoiceRequest.json'; import * as createInvoiceResponseMcok from './json/createInvoiceResponse.json'; @@ -66,9 +67,11 @@ import * as getSettlementsResponseMock from './json/getSettlementsResponse.json' import * as getSettlementResponseMock from './json/getSettlementResponse.json'; import * as getSettlementReconciliationReportResponseMock from './json/getSettlementReconciliationReportResponse.json'; import * as getSupportedWalletsMock from './json/getSupportedWallets.json'; +import * as invalidSignature from './json/invalidSignature.json'; import { isEqual } from 'lodash'; import * as BitPaySDK from '../src/index'; +import BitPayApiException from '../src/Exceptions/BitPayApiException'; let client; let oneMonthAgo; @@ -179,6 +182,58 @@ describe('BitPaySDK.Client', () => { }); }); + describe('Exceptions', () => { + const hexPrivate = '2f72ed3291b536aa43d750829875f5a742a0f1095b8ad529944cbc0bd498693g'; + const ecKey = keyUtils.load_keypair(hexPrivate); + const tokenContainer = new TokenContainer(); + tokenContainer.addMerchant(merchantToken); + tokenContainer.addPayout(payoutToken); + + const client = new Client( + null, + null, + tokenContainer, + null, + null, + undefined, + new BitPayClient(host + '/', ecKey, 'someIdentity'), + null + ); + + it('should throws BitPayException for invalid signature', async () => { + server.use( + rest.get(host + '/invoices/1234', async (req, res, ctx) => { + validateSignatureRequest(req); + validateMerchantTokenInUrl(req); + + return res(ctx.status(200), ctx.json(invalidSignature)); + }) + ); + + await expect(client.getInvoice('1234')).rejects.toBeInstanceOf(BitPayApiException); + await expect(client.getInvoice('1234')).rejects.toEqual({ + code: '000000', + message: 'Invalid signature', + name: 'BITPAY-EXCEPTION' + }); + }); + it('should throws BitPayException for error response', async () => { + server.use( + rest.post(host + '/payouts', async (req, res, ctx) => { + return res(ctx.status(200), ctx.json(errorResponse)); + }) + ); + + const payout: Payout = new Payout(10.0, 'USD', 'USD'); + await expect(client.submitPayout(payout)).rejects.toBeInstanceOf(BitPayApiException); + await expect(client.submitPayout(payout)).rejects.toEqual({ + code: '0000', + message: '["Currency disabled for user location."]', + name: 'BITPAY-EXCEPTION' + }); + }); + }); + describe('Bill', () => { function getBill() { const item1 = new Item(); diff --git a/test/json/errorResponse.json b/test/json/errorResponse.json new file mode 100644 index 0000000..aea4952 --- /dev/null +++ b/test/json/errorResponse.json @@ -0,0 +1,7 @@ +{ + "status": "error", + "code": "0000", + "data": null, + "error": "[\"Currency disabled for user location.\"]", + "message": "[\"Currency disabled for user location.\"]" +} \ No newline at end of file diff --git a/test/json/invalidSignature.json b/test/json/invalidSignature.json new file mode 100644 index 0000000..60f232c --- /dev/null +++ b/test/json/invalidSignature.json @@ -0,0 +1,3 @@ +{ + "error": "Invalid signature" +} \ No newline at end of file