80 lines
No EOL
2.1 KiB
JavaScript
80 lines
No EOL
2.1 KiB
JavaScript
export default defineEventHandler(async (event) => {
|
|
const query = getQuery(event)
|
|
const { source = 'EUR', target = 'CAD' } = query
|
|
|
|
// Get API token from environment variables (use Jennie's token by default)
|
|
const apiToken = process.env.WISE_API_KEY_JENNIE
|
|
|
|
if (!apiToken) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: 'Wise API token not configured'
|
|
})
|
|
}
|
|
|
|
try {
|
|
// First get the profile ID
|
|
const profileResponse = await fetch('https://api.wise.com/v1/profiles', {
|
|
headers: {
|
|
'Authorization': `Bearer ${apiToken}`,
|
|
'Content-Type': 'application/json'
|
|
}
|
|
})
|
|
|
|
if (!profileResponse.ok) {
|
|
throw new Error(`Profile fetch failed: ${profileResponse.statusText}`)
|
|
}
|
|
|
|
const profiles = await profileResponse.json()
|
|
const personalProfile = profiles.find(p => p.type === 'personal')
|
|
|
|
if (!personalProfile) {
|
|
throw new Error('Personal profile not found')
|
|
}
|
|
|
|
// Get exchange rates
|
|
const ratesResponse = await fetch(`https://api.wise.com/v1/rates?source=${source}&target=${target}`, {
|
|
headers: {
|
|
'Authorization': `Bearer ${apiToken}`,
|
|
'Content-Type': 'application/json'
|
|
}
|
|
})
|
|
|
|
if (!ratesResponse.ok) {
|
|
throw new Error(`Exchange rates fetch failed: ${ratesResponse.statusText}`)
|
|
}
|
|
|
|
const rates = await ratesResponse.json()
|
|
|
|
// Return the rate and timestamp
|
|
return {
|
|
source,
|
|
target,
|
|
rate: rates[0]?.rate || null,
|
|
timestamp: new Date().toISOString(),
|
|
rateType: rates[0]?.type || 'unknown'
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error(`Wise exchange rate API error:`, error)
|
|
|
|
// Fallback to hardcoded rate if API fails
|
|
const fallbackRates = {
|
|
'EUR-CAD': 1.45,
|
|
'USD-CAD': 1.35,
|
|
'GBP-CAD': 1.65
|
|
}
|
|
|
|
const fallbackKey = `${source}-${target}`
|
|
const fallbackRate = fallbackRates[fallbackKey] || 1.0
|
|
|
|
return {
|
|
source,
|
|
target,
|
|
rate: fallbackRate,
|
|
timestamp: new Date().toISOString(),
|
|
rateType: 'fallback',
|
|
error: 'Using fallback rate due to API error'
|
|
}
|
|
}
|
|
}) |