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:
parent
f275d317ed
commit
e5054fdb9d
2 changed files with 45 additions and 40 deletions
|
|
@ -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
|
||||||
|
|
@ -32,14 +33,21 @@ 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[]>([])
|
||||||
private _isCreatingPayLink = ref(false)
|
private _isCreatingPayLink = ref(false)
|
||||||
private _isSendingPayment = ref(false)
|
private _isSendingPayment = ref(false)
|
||||||
private _error = ref<string | null>(null)
|
private _error = ref<string | null>(null)
|
||||||
|
|
||||||
// Public reactive getters
|
// Public reactive getters
|
||||||
readonly payLinks = computed(() => this._payLinks.value)
|
readonly payLinks = computed(() => this._payLinks.value)
|
||||||
readonly transactions = computed(() => this._transactions.value)
|
readonly transactions = computed(() => this._transactions.value)
|
||||||
|
|
@ -47,25 +55,22 @@ 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) {
|
||||||
throw new Error('Payment service not available')
|
throw new Error('Payment service not available')
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load initial data
|
// Load initial data
|
||||||
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,15 +200,15 @@ 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()
|
||||||
|
|
||||||
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
|
||||||
|
|
@ -236,11 +241,11 @@ export default class WalletService extends BaseService {
|
||||||
lnurl: `${baseUrl}/lnurlp/${link.id}`,
|
lnurl: `${baseUrl}/lnurlp/${link.id}`,
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
@ -270,14 +275,14 @@ export default class WalletService extends BaseService {
|
||||||
type: payment.amount > 0 ? 'received' : 'sent',
|
type: payment.amount > 0 ? 'received' : 'sent',
|
||||||
status: payment.pending ? 'pending' : 'confirmed',
|
status: payment.pending ? 'pending' : 'confirmed',
|
||||||
fee: payment.fee
|
fee: payment.fee
|
||||||
})).sort((a: PaymentTransaction, b: PaymentTransaction) =>
|
})).sort((a: PaymentTransaction, b: PaymentTransaction) =>
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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) {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue