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.
This commit is contained in:
padreug 2025-09-14 23:20:05 +02:00
parent f275d317ed
commit e5054fdb9d
2 changed files with 45 additions and 40 deletions

View file

@ -1,6 +1,7 @@
import { ref, computed } from 'vue' import { ref, computed } from 'vue'
import { BaseService } from '@/core/base/BaseService' import { BaseService } from '@/core/base/BaseService'
import { injectService, SERVICE_TOKENS } from '@/core/di-container' import { injectService, SERVICE_TOKENS } from '@/core/di-container'
import { config } from '@/lib/config'
export interface PayLink { export interface PayLink {
id: string id: string
@ -33,6 +34,13 @@ export interface PaymentTransaction {
export default class WalletService extends BaseService { export default class WalletService extends BaseService {
private paymentService: any = null private paymentService: any = null
// Required metadata for BaseService
protected readonly metadata = {
name: 'WalletService',
version: '1.0.0',
dependencies: [] // No specific dependencies
}
// Reactive state // Reactive state
private _payLinks = ref<PayLink[]>([]) private _payLinks = ref<PayLink[]>([])
private _transactions = ref<PaymentTransaction[]>([]) private _transactions = ref<PaymentTransaction[]>([])
@ -47,11 +55,7 @@ export default class WalletService extends BaseService {
readonly isSendingPayment = computed(() => this._isSendingPayment.value) readonly isSendingPayment = computed(() => this._isSendingPayment.value)
readonly error = computed(() => this._error.value) readonly error = computed(() => this._error.value)
constructor() { protected async onInitialize(): Promise<void> {
super('WalletService')
}
async initialize(): Promise<void> {
try { try {
this.paymentService = injectService(SERVICE_TOKENS.PAYMENT_SERVICE) this.paymentService = injectService(SERVICE_TOKENS.PAYMENT_SERVICE)
if (!this.paymentService) { if (!this.paymentService) {
@ -62,10 +66,11 @@ export default class WalletService extends BaseService {
await this.loadPayLinks() await this.loadPayLinks()
await this.loadTransactions() await this.loadTransactions()
this.logger.info('WalletService initialized successfully') console.log('WalletService initialized successfully')
} catch (error) { } 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' 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 // 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', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -119,7 +124,7 @@ export default class WalletService extends BaseService {
const payLink: PayLink = await response.json() const payLink: PayLink = await response.json()
// Generate the LNURL and Lightning Address // Generate the LNURL and Lightning Address
const baseUrl = this.paymentService.config.baseUrl const baseUrl = config.api.baseUrl
payLink.lnurl = `${baseUrl}/lnurlp/${payLink.id}` payLink.lnurl = `${baseUrl}/lnurlp/${payLink.id}`
if (payLink.username) { if (payLink.username) {
@ -129,12 +134,12 @@ export default class WalletService extends BaseService {
} }
this._payLinks.value.unshift(payLink) this._payLinks.value.unshift(payLink)
this.logger.info('Created new pay link:', payLink.id) console.log('Created new pay link:', payLink.id)
return payLink return payLink
} catch (error) { } 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' this._error.value = error instanceof Error ? error.message : 'Failed to create receive address'
return null return null
} finally { } finally {
@ -161,14 +166,14 @@ export default class WalletService extends BaseService {
// Determine payment type and prepare request // Determine payment type and prepare request
if (request.destination.startsWith('ln')) { if (request.destination.startsWith('ln')) {
// Lightning invoice // Lightning invoice
endpoint = `${this.paymentService.config.baseUrl}/api/v1/payments` endpoint = `${config.api.baseUrl}/api/v1/payments`
body = { body = {
out: true, out: true,
bolt11: request.destination bolt11: request.destination
} }
} else if (request.destination.includes('@') || request.destination.toLowerCase().startsWith('lnurl')) { } else if (request.destination.includes('@') || request.destination.toLowerCase().startsWith('lnurl')) {
// Lightning address or LNURL // Lightning address or LNURL
endpoint = `${this.paymentService.config.baseUrl}/api/v1/payments/lnurl` endpoint = `${config.api.baseUrl}/api/v1/payments/lnurl`
body = { body = {
lnurl: request.destination.includes('@') lnurl: request.destination.includes('@')
? `https://${request.destination.split('@')[1]}/.well-known/lnurlp/${request.destination.split('@')[0]}` ? `https://${request.destination.split('@')[1]}/.well-known/lnurlp/${request.destination.split('@')[0]}`
@ -195,7 +200,7 @@ export default class WalletService extends BaseService {
} }
const payment = await response.json() const payment = await response.json()
this.logger.info('Payment sent successfully:', payment.payment_hash) console.log('Payment sent successfully:', payment.payment_hash)
// Refresh transactions // Refresh transactions
await this.loadTransactions() await this.loadTransactions()
@ -203,7 +208,7 @@ export default class WalletService extends BaseService {
return true return true
} catch (error) { } 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' this._error.value = error instanceof Error ? error.message : 'Payment failed'
return false return false
} finally { } finally {
@ -219,7 +224,7 @@ export default class WalletService extends BaseService {
const adminKey = this.paymentService?.getPreferredWalletAdminKey() const adminKey = this.paymentService?.getPreferredWalletAdminKey()
if (!adminKey) return 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: { headers: {
'X-Api-Key': adminKey 'X-Api-Key': adminKey
} }
@ -227,7 +232,7 @@ export default class WalletService extends BaseService {
if (response.ok) { if (response.ok) {
const links = await response.json() const links = await response.json()
const baseUrl = this.paymentService.config.baseUrl const baseUrl = config.api.baseUrl
const domain = new URL(baseUrl).hostname const domain = new URL(baseUrl).hostname
// Add LNURL and Lightning Address to each link // Add LNURL and Lightning Address to each link
@ -237,10 +242,10 @@ export default class WalletService extends BaseService {
lnaddress: link.username ? `${link.username}@${domain}` : undefined lnaddress: link.username ? `${link.username}@${domain}` : undefined
})) }))
this.logger.info(`Loaded ${links.length} pay links`) console.log(`Loaded ${links.length} pay links`)
} }
} catch (error) { } 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() const invoiceKey = this.paymentService?.getPreferredWalletInvoiceKey()
if (!invoiceKey) return 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: { headers: {
'X-Api-Key': invoiceKey 'X-Api-Key': invoiceKey
} }
@ -274,10 +279,10 @@ export default class WalletService extends BaseService {
b.timestamp.getTime() - a.timestamp.getTime() b.timestamp.getTime() - a.timestamp.getTime()
) )
this.logger.info(`Loaded ${payments.length} transactions`) console.log(`Loaded ${payments.length} transactions`)
} }
} catch (error) { } 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') 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', method: 'DELETE',
headers: { headers: {
'X-Api-Key': adminKey 'X-Api-Key': adminKey
@ -304,12 +309,12 @@ export default class WalletService extends BaseService {
// Remove from local state // Remove from local state
this._payLinks.value = this._payLinks.value.filter(link => link.id !== linkId) 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 return true
} catch (error) { } 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' this._error.value = error instanceof Error ? error.message : 'Failed to delete pay link'
return false return false
} }

View file

@ -54,7 +54,7 @@ const groupedTransactions = computed(() => {
async function refresh() { async function refresh() {
await walletService?.refresh() await walletService?.refresh()
// Also refresh auth data to update balance // Also refresh auth data to update balance
await authService?.refreshUserData() await authService?.refresh()
} }
function getTransactionIcon(type: string) { function getTransactionIcon(type: string) {