refactor(helcim): use centralized helper in 5 simple endpoints

This commit is contained in:
Jennie Robinson Faber 2026-04-08 21:44:18 +01:00
parent 07e005ebfc
commit 7b4b6feb51
5 changed files with 66 additions and 296 deletions

View file

@ -2,8 +2,7 @@
import jwt from 'jsonwebtoken'
import Member from '../../models/member.js'
import { connectDB } from '../../utils/mongoose.js'
const HELCIM_API_BASE = 'https://api.helcim.com/v2'
import { createHelcimCustomer } from '../../utils/helcim.js'
export default defineEventHandler(async (event) => {
try {
@ -20,65 +19,12 @@ export default defineEventHandler(async (event) => {
})
}
// Get token directly from environment if not in config
const helcimToken = config.helcimApiToken
if (!helcimToken) {
throw createError({
statusCode: 500,
statusMessage: 'Helcim API token not configured'
})
}
// Test the connection first with native fetch
try {
const testResponse = await fetch('https://api.helcim.com/v2/connection-test', {
method: 'GET',
headers: {
'accept': 'application/json',
'api-token': helcimToken
}
})
if (!testResponse.ok) {
throw new Error(`HTTP ${testResponse.status}: ${testResponse.statusText}`)
}
await testResponse.json()
} catch (testError) {
console.error('Connection test failed:', testError)
throw createError({
statusCode: 401,
statusMessage: 'Payment service unavailable'
})
}
// Create customer in Helcim using native fetch
const customerResponse = await fetch(`${HELCIM_API_BASE}/customers`, {
method: 'POST',
headers: {
'accept': 'application/json',
'content-type': 'application/json',
'api-token': helcimToken
},
body: JSON.stringify({
customerType: 'PERSON',
contactName: body.name,
email: body.email
})
// Create customer in Helcim
const customerData = await createHelcimCustomer({
customerType: 'PERSON',
contactName: body.name,
email: body.email
})
if (!customerResponse.ok) {
const errorText = await customerResponse.text()
console.error('Customer creation failed:', customerResponse.status, errorText)
throw createError({
statusCode: customerResponse.status,
statusMessage: 'Customer creation failed'
})
}
const customerData = await customerResponse.json()
// Create member in database
const member = await Member.create({
@ -92,10 +38,10 @@ export default defineEventHandler(async (event) => {
// Generate JWT token for the session
const token = jwt.sign(
{
{
memberId: member._id,
email: body.email,
helcimCustomerId: customerData.id
helcimCustomerId: customerData.id
},
config.jwtSecret,
{ expiresIn: '7d' }
@ -132,4 +78,4 @@ export default defineEventHandler(async (event) => {
statusMessage: 'An unexpected error occurred'
})
}
})
})