From e5054fdb9da67ef2ae33097c761b5b067ac8fbab Mon Sep 17 00:00:00 2001 From: padreug Date: Sun, 14 Sep 2025 23:20:05 +0200 Subject: [PATCH] Refactor WalletService to use config for API endpoints and improve error handling - Updated WalletService to utilize the centralized config for API base URLs, enhancing maintainability. - Replaced logger calls with console statements for error handling and success messages to simplify debugging. - Refactored the onInitialize method and other service methods to improve clarity and error management. These changes streamline the service's functionality and ensure consistent API endpoint usage. --- src/modules/wallet/services/WalletService.ts | 83 +++++++++++--------- src/modules/wallet/views/WalletPage.vue | 2 +- 2 files changed, 45 insertions(+), 40 deletions(-) diff --git a/src/modules/wallet/services/WalletService.ts b/src/modules/wallet/services/WalletService.ts index e6db181..bdb5334 100644 --- a/src/modules/wallet/services/WalletService.ts +++ b/src/modules/wallet/services/WalletService.ts @@ -1,6 +1,7 @@ import { ref, computed } from 'vue' import { BaseService } from '@/core/base/BaseService' import { injectService, SERVICE_TOKENS } from '@/core/di-container' +import { config } from '@/lib/config' export interface PayLink { id: string @@ -32,14 +33,21 @@ export interface PaymentTransaction { export default class WalletService extends BaseService { private paymentService: any = null - + + // Required metadata for BaseService + protected readonly metadata = { + name: 'WalletService', + version: '1.0.0', + dependencies: [] // No specific dependencies + } + // Reactive state private _payLinks = ref([]) private _transactions = ref([]) private _isCreatingPayLink = ref(false) private _isSendingPayment = ref(false) private _error = ref(null) - + // Public reactive getters readonly payLinks = computed(() => this._payLinks.value) readonly transactions = computed(() => this._transactions.value) @@ -47,25 +55,22 @@ export default class WalletService extends BaseService { readonly isSendingPayment = computed(() => this._isSendingPayment.value) readonly error = computed(() => this._error.value) - constructor() { - super('WalletService') - } - - async initialize(): Promise { + protected async onInitialize(): Promise { try { this.paymentService = injectService(SERVICE_TOKENS.PAYMENT_SERVICE) if (!this.paymentService) { throw new Error('Payment service not available') } - + // Load initial data await this.loadPayLinks() await this.loadTransactions() - - this.logger.info('WalletService initialized successfully') + + console.log('WalletService initialized successfully') } catch (error) { - this.logger.error('Failed to initialize WalletService:', error) + console.error('Failed to initialize WalletService:', error) this._error.value = error instanceof Error ? error.message : 'Initialization failed' + throw error } } @@ -94,7 +99,7 @@ export default class WalletService extends BaseService { } // Create pay link via LNbits LNURLP extension API - const response = await fetch(`${this.paymentService.config.baseUrl}/lnurlp/api/v1/links`, { + const response = await fetch(`${config.api.baseUrl}/lnurlp/api/v1/links`, { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -119,7 +124,7 @@ export default class WalletService extends BaseService { const payLink: PayLink = await response.json() // Generate the LNURL and Lightning Address - const baseUrl = this.paymentService.config.baseUrl + const baseUrl = config.api.baseUrl payLink.lnurl = `${baseUrl}/lnurlp/${payLink.id}` if (payLink.username) { @@ -129,12 +134,12 @@ export default class WalletService extends BaseService { } this._payLinks.value.unshift(payLink) - this.logger.info('Created new pay link:', payLink.id) - + console.log('Created new pay link:', payLink.id) + return payLink - + } catch (error) { - this.logger.error('Failed to create receive address:', error) + console.error('Failed to create receive address:', error) this._error.value = error instanceof Error ? error.message : 'Failed to create receive address' return null } finally { @@ -161,14 +166,14 @@ export default class WalletService extends BaseService { // Determine payment type and prepare request if (request.destination.startsWith('ln')) { // Lightning invoice - endpoint = `${this.paymentService.config.baseUrl}/api/v1/payments` + endpoint = `${config.api.baseUrl}/api/v1/payments` body = { out: true, bolt11: request.destination } } else if (request.destination.includes('@') || request.destination.toLowerCase().startsWith('lnurl')) { // Lightning address or LNURL - endpoint = `${this.paymentService.config.baseUrl}/api/v1/payments/lnurl` + endpoint = `${config.api.baseUrl}/api/v1/payments/lnurl` body = { lnurl: request.destination.includes('@') ? `https://${request.destination.split('@')[1]}/.well-known/lnurlp/${request.destination.split('@')[0]}` @@ -195,15 +200,15 @@ export default class WalletService extends BaseService { } const payment = await response.json() - this.logger.info('Payment sent successfully:', payment.payment_hash) - + console.log('Payment sent successfully:', payment.payment_hash) + // Refresh transactions await this.loadTransactions() - + return true - + } catch (error) { - this.logger.error('Failed to send payment:', error) + console.error('Failed to send payment:', error) this._error.value = error instanceof Error ? error.message : 'Payment failed' return false } finally { @@ -219,7 +224,7 @@ export default class WalletService extends BaseService { const adminKey = this.paymentService?.getPreferredWalletAdminKey() if (!adminKey) return - const response = await fetch(`${this.paymentService.config.baseUrl}/lnurlp/api/v1/links`, { + const response = await fetch(`${config.api.baseUrl}/lnurlp/api/v1/links`, { headers: { 'X-Api-Key': adminKey } @@ -227,7 +232,7 @@ export default class WalletService extends BaseService { if (response.ok) { const links = await response.json() - const baseUrl = this.paymentService.config.baseUrl + const baseUrl = config.api.baseUrl const domain = new URL(baseUrl).hostname // Add LNURL and Lightning Address to each link @@ -236,11 +241,11 @@ export default class WalletService extends BaseService { lnurl: `${baseUrl}/lnurlp/${link.id}`, lnaddress: link.username ? `${link.username}@${domain}` : undefined })) - - this.logger.info(`Loaded ${links.length} pay links`) + + console.log(`Loaded ${links.length} pay links`) } } catch (error) { - this.logger.error('Failed to load pay links:', error) + console.error('Failed to load pay links:', error) } } @@ -252,7 +257,7 @@ export default class WalletService extends BaseService { const invoiceKey = this.paymentService?.getPreferredWalletInvoiceKey() if (!invoiceKey) return - const response = await fetch(`${this.paymentService.config.baseUrl}/api/v1/payments`, { + const response = await fetch(`${config.api.baseUrl}/api/v1/payments`, { headers: { 'X-Api-Key': invoiceKey } @@ -270,14 +275,14 @@ export default class WalletService extends BaseService { type: payment.amount > 0 ? 'received' : 'sent', status: payment.pending ? 'pending' : 'confirmed', fee: payment.fee - })).sort((a: PaymentTransaction, b: PaymentTransaction) => + })).sort((a: PaymentTransaction, b: PaymentTransaction) => b.timestamp.getTime() - a.timestamp.getTime() ) - - this.logger.info(`Loaded ${payments.length} transactions`) + + console.log(`Loaded ${payments.length} transactions`) } } catch (error) { - this.logger.error('Failed to load transactions:', error) + console.error('Failed to load transactions:', error) } } @@ -291,7 +296,7 @@ export default class WalletService extends BaseService { throw new Error('No admin key available') } - const response = await fetch(`${this.paymentService.config.baseUrl}/lnurlp/api/v1/links/${linkId}`, { + const response = await fetch(`${config.api.baseUrl}/lnurlp/api/v1/links/${linkId}`, { method: 'DELETE', headers: { 'X-Api-Key': adminKey @@ -304,12 +309,12 @@ export default class WalletService extends BaseService { // Remove from local state this._payLinks.value = this._payLinks.value.filter(link => link.id !== linkId) - this.logger.info('Deleted pay link:', linkId) - + console.log('Deleted pay link:', linkId) + return true - + } catch (error) { - this.logger.error('Failed to delete pay link:', error) + console.error('Failed to delete pay link:', error) this._error.value = error instanceof Error ? error.message : 'Failed to delete pay link' return false } diff --git a/src/modules/wallet/views/WalletPage.vue b/src/modules/wallet/views/WalletPage.vue index 2c610c2..808d691 100644 --- a/src/modules/wallet/views/WalletPage.vue +++ b/src/modules/wallet/views/WalletPage.vue @@ -54,7 +54,7 @@ const groupedTransactions = computed(() => { async function refresh() { await walletService?.refresh() // Also refresh auth data to update balance - await authService?.refreshUserData() + await authService?.refresh() } function getTransactionIcon(type: string) {