refactor: Complete Phase 3 - Migrate API route handlers from core to utilities

- Created dedicated utility functions for API route proxies (buildApiUrl, extractHeaders, handleApiError)
- Migrated all 20 API route handlers to use new utilities instead of api/core
- Routes continue to act as proxies to Rails API (correct architecture)
- Removed dependency on buildUrl from api/core in all route handlers
- Updated migration plan to reflect completed Phase 3
This commit is contained in:
Justin Edmund 2025-09-20 01:11:08 -07:00
parent 87a65408f9
commit 8332ecc158
21 changed files with 117 additions and 98 deletions

55
src/routes/api/_utils.ts Normal file
View file

@ -0,0 +1,55 @@
import { PUBLIC_SIERO_API_URL } from '$env/static/public'
/**
* Utility functions for API route handlers
* These routes act as proxies to the Rails API
*/
export const API_BASE = new URL(PUBLIC_SIERO_API_URL || 'http://localhost:3000').href
/**
* Build a full URL for the Rails API
*/
export function buildApiUrl(path: string, params?: Record<string, any>): string {
const url = new URL(path.startsWith('http') ? path : `${API_BASE}${path}`, API_BASE)
if (params) {
for (const [key, value] of Object.entries(params)) {
if (value === undefined || value === null) continue
if (Array.isArray(value)) {
value.forEach((x) => url.searchParams.append(key, String(x)))
} else {
url.searchParams.set(key, String(value))
}
}
}
return url.toString()
}
/**
* Extract headers that should be forwarded to the Rails API
*/
export function extractHeaders(request: Request): Record<string, string> {
const headers: Record<string, string> = {
'Content-Type': 'application/json'
}
const editKey = request.headers.get('X-Edit-Key')
if (editKey) {
headers['X-Edit-Key'] = editKey
}
return headers
}
/**
* Common error handler for API routes
*/
export function handleApiError(error: any, action: string) {
console.error(`Error ${action}:`, error)
return {
error: `Failed to ${action}`,
details: error instanceof Error ? error.message : 'Unknown error'
}
}

View file

@ -1,8 +1,5 @@
import { json, type RequestHandler } from '@sveltejs/kit'
import { buildUrl } from '$lib/api/core'
import { PUBLIC_SIERO_API_URL } from '$env/static/public'
const API_BASE = new URL(PUBLIC_SIERO_API_URL || 'http://localhost:3000').href
import { buildApiUrl, extractHeaders, handleApiError } from '../_utils'
/**
* POST /api/parties - Create a new party
@ -11,33 +8,19 @@ const API_BASE = new URL(PUBLIC_SIERO_API_URL || 'http://localhost:3000').href
export const POST: RequestHandler = async ({ request, fetch }) => {
try {
const body = await request.json()
const editKey = request.headers.get('X-Edit-Key')
const headers = extractHeaders(request)
// Forward to Rails API
// The server-side fetch will automatically add Bearer token if user is authenticated
const response = await fetch(buildUrl('/parties'), {
const response = await fetch(buildApiUrl('/parties'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(editKey ? { 'X-Edit-Key': editKey } : {})
},
headers,
body: JSON.stringify(body)
})
const data = await response.json()
// If creation was successful and returned an edit key, include it in response
if (response.ok) {
return json(data, { status: response.status })
}
// Forward error response
return json(data, { status: response.status })
} catch (error) {
console.error('Error creating party:', error)
return json(
{ error: 'Failed to create party' },
{ status: 500 }
)
return json(handleApiError(error, 'create party'), { status: 500 })
}
}

View file

@ -1,5 +1,5 @@
import { json, type RequestHandler } from '@sveltejs/kit'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../_utils'
/**
* PUT /api/parties/[id] - Update a party
@ -11,41 +11,31 @@ export const PUT: RequestHandler = async ({ request, params, fetch }) => {
try {
const { id } = params
const body = await request.json()
const editKey = request.headers.get('X-Edit-Key')
const headers = extractHeaders(request)
// Forward to Rails API
const response = await fetch(buildUrl(`/parties/${id}`), {
const response = await fetch(buildApiUrl(`/parties/${id}`), {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
...(editKey ? { 'X-Edit-Key': editKey } : {})
},
headers,
body: JSON.stringify(body)
})
const data = await response.json()
return json(data, { status: response.status })
} catch (error) {
console.error('Error updating party:', error)
return json(
{ error: 'Failed to update party' },
{ status: 500 }
)
return json(handleApiError(error, 'update party'), { status: 500 })
}
}
export const DELETE: RequestHandler = async ({ request, params, fetch }) => {
try {
const { id } = params
const editKey = request.headers.get('X-Edit-Key')
const headers = extractHeaders(request)
// Forward to Rails API
const response = await fetch(buildUrl(`/parties/${id}`), {
const response = await fetch(buildApiUrl(`/parties/${id}`), {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
...(editKey ? { 'X-Edit-Key': editKey } : {})
}
headers
})
if (response.ok) {
@ -57,10 +47,6 @@ export const DELETE: RequestHandler = async ({ request, params, fetch }) => {
const errorData = await response.json().catch(() => ({}))
return json(errorData, { status: response.status })
} catch (error) {
console.error('Error deleting party:', error)
return json(
{ error: 'Failed to delete party' },
{ status: 500 }
)
return json(handleApiError(error, 'delete party'), { status: 500 })
}
}

View file

@ -1,5 +1,5 @@
import { json, type RequestHandler } from '@sveltejs/kit'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../../_utils'
/**
* POST /api/parties/[id]/characters - Add character to party
@ -25,7 +25,7 @@ export const POST: RequestHandler = async ({ request, params, fetch }) => {
}
// Forward to Rails API
const response = await fetch(buildUrl('/characters'), {
const response = await fetch(buildApiUrl('/characters'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@ -51,7 +51,7 @@ export const DELETE: RequestHandler = async ({ request, params, fetch }) => {
const editKey = request.headers.get('X-Edit-Key')
// Forward to Rails API - use grid_characters endpoint with the ID
const response = await fetch(buildUrl(`/grid_characters/${body.gridCharacterId}`), {
const response = await fetch(buildApiUrl(`/grid_characters/${body.gridCharacterId}`), {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',

View file

@ -1,5 +1,5 @@
import { json, type RequestHandler } from '@sveltejs/kit'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../../../_utils'
/**
* PUT /api/parties/[id]/characters/[characterId] - Update character in party
@ -17,7 +17,7 @@ export const PUT: RequestHandler = async ({ request, params, fetch }) => {
}
// Forward to Rails API
const response = await fetch(buildUrl(`/grid_characters/${params.characterId}`), {
const response = await fetch(buildApiUrl(`/grid_characters/${params.characterId}`), {
method: 'PUT',
headers: {
'Content-Type': 'application/json',

View file

@ -1,5 +1,5 @@
import { json, type RequestHandler } from '@sveltejs/kit'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../../_utils'
/**
* POST /api/parties/[id]/grid_characters - Add character to party
@ -12,7 +12,7 @@ export const POST: RequestHandler = async ({ request, params, fetch, cookies })
const editKey = request.headers.get('X-Edit-Key')
// Forward to Rails API
const response = await fetch(buildUrl('/characters'), {
const response = await fetch(buildApiUrl('/characters'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',

View file

@ -1,6 +1,6 @@
import { json } from '@sveltejs/kit'
import type { RequestHandler } from './$types'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../../../../_utils'
export const PUT: RequestHandler = async ({ params, request, fetch, cookies }) => {
const { id: partyId, characterId } = params
@ -9,7 +9,7 @@ export const PUT: RequestHandler = async ({ params, request, fetch, cookies }) =
// Forward the request to the Rails API
const apiResponse = await fetch(
buildUrl(`/parties/${partyId}/grid_characters/${characterId}/position`),
buildApiUrl(`/parties/${partyId}/grid_characters/${characterId}/position`),
{
method: 'PUT',
headers: {

View file

@ -1,6 +1,6 @@
import { json } from '@sveltejs/kit'
import type { RequestHandler } from './$types'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../../../_utils'
export const POST: RequestHandler = async ({ params, request, fetch, cookies }) => {
const { id: partyId } = params
@ -9,7 +9,7 @@ export const POST: RequestHandler = async ({ params, request, fetch, cookies })
// Forward the request to the Rails API
const apiResponse = await fetch(
buildUrl(`/parties/${partyId}/grid_characters/swap`),
buildApiUrl(`/parties/${partyId}/grid_characters/swap`),
{
method: 'POST',
headers: {

View file

@ -1,5 +1,5 @@
import { json, type RequestHandler } from '@sveltejs/kit'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../../_utils'
/**
* POST /api/parties/[id]/grid_summons - Add summon to party
@ -12,7 +12,7 @@ export const POST: RequestHandler = async ({ request, params, fetch, cookies })
const editKey = request.headers.get('X-Edit-Key')
// Forward to Rails API
const response = await fetch(buildUrl('/summons'), {
const response = await fetch(buildApiUrl('/summons'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',

View file

@ -1,6 +1,6 @@
import { json } from '@sveltejs/kit'
import type { RequestHandler } from './$types'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../../../../_utils'
export const PUT: RequestHandler = async ({ params, request, fetch, cookies }) => {
const { id: partyId, summonId } = params
@ -9,7 +9,7 @@ export const PUT: RequestHandler = async ({ params, request, fetch, cookies }) =
// Forward the request to the Rails API
const apiResponse = await fetch(
buildUrl(`/parties/${partyId}/grid_summons/${summonId}/position`),
buildApiUrl(`/parties/${partyId}/grid_summons/${summonId}/position`),
{
method: 'PUT',
headers: {

View file

@ -1,6 +1,6 @@
import { json } from '@sveltejs/kit'
import type { RequestHandler } from './$types'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../../../_utils'
export const POST: RequestHandler = async ({ params, request, fetch, cookies }) => {
const { id: partyId } = params
@ -9,7 +9,7 @@ export const POST: RequestHandler = async ({ params, request, fetch, cookies })
// Forward the request to the Rails API
const apiResponse = await fetch(
buildUrl(`/parties/${partyId}/grid_summons/swap`),
buildApiUrl(`/parties/${partyId}/grid_summons/swap`),
{
method: 'POST',
headers: {

View file

@ -1,5 +1,5 @@
import { json, type RequestHandler } from '@sveltejs/kit'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../../_utils'
/**
* POST /api/parties/[id]/grid_weapons - Add weapon to party
@ -9,16 +9,15 @@ import { buildUrl } from '$lib/api/core'
export const POST: RequestHandler = async ({ request, params, fetch, cookies }) => {
try {
const body = await request.json()
const editKey = request.headers.get('X-Edit-Key')
const headers = {
...extractHeaders(request),
Authorization: `Bearer ${cookies.get('access_token')}`
}
// Forward to Rails API
const response = await fetch(buildUrl('/weapons'), {
const response = await fetch(buildApiUrl('/weapons'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${cookies.get('access_token')}`,
...(editKey ? { 'X-Edit-Key': editKey } : {})
},
headers,
body: JSON.stringify({
weapon: {
party_id: params.id,
@ -30,10 +29,6 @@ export const POST: RequestHandler = async ({ request, params, fetch, cookies })
const data = await response.json()
return json(data, { status: response.status })
} catch (error) {
console.error('Error adding weapon:', error)
return json(
{ error: 'Failed to add weapon' },
{ status: 500 }
)
return json(handleApiError(error, 'add weapon'), { status: 500 })
}
}

View file

@ -1,6 +1,6 @@
import { json } from '@sveltejs/kit'
import type { RequestHandler } from './$types'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../../../../_utils'
export const PUT: RequestHandler = async ({ params, request, fetch, cookies }) => {
const { id: partyId, weaponId } = params
@ -9,7 +9,7 @@ export const PUT: RequestHandler = async ({ params, request, fetch, cookies }) =
// Forward the request to the Rails API
const apiResponse = await fetch(
buildUrl(`/parties/${partyId}/grid_weapons/${weaponId}/position`),
buildApiUrl(`/parties/${partyId}/grid_weapons/${weaponId}/position`),
{
method: 'PUT',
headers: {

View file

@ -1,6 +1,6 @@
import { json } from '@sveltejs/kit'
import type { RequestHandler } from './$types'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../../../_utils'
export const POST: RequestHandler = async ({ params, request, fetch, cookies }) => {
const { id: partyId } = params
@ -9,7 +9,7 @@ export const POST: RequestHandler = async ({ params, request, fetch, cookies })
// Forward the request to the Rails API
const apiResponse = await fetch(
buildUrl(`/parties/${partyId}/grid_weapons/swap`),
buildApiUrl(`/parties/${partyId}/grid_weapons/swap`),
{
method: 'POST',
headers: {

View file

@ -1,5 +1,5 @@
import { json, type RequestHandler } from '@sveltejs/kit'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../../_utils'
/**
* POST /api/parties/[id]/summons - Add summon to party
@ -27,7 +27,7 @@ export const POST: RequestHandler = async ({ request, params, fetch }) => {
}
// Forward to Rails API
const response = await fetch(buildUrl('/summons'), {
const response = await fetch(buildApiUrl('/summons'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@ -53,7 +53,7 @@ export const DELETE: RequestHandler = async ({ request, params, fetch }) => {
const editKey = request.headers.get('X-Edit-Key')
// Forward to Rails API - use grid_summons endpoint with the ID
const response = await fetch(buildUrl(`/grid_summons/${body.gridSummonId}`), {
const response = await fetch(buildApiUrl(`/grid_summons/${body.gridSummonId}`), {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',

View file

@ -1,5 +1,5 @@
import { json, type RequestHandler } from '@sveltejs/kit'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../../../_utils'
/**
* PUT /api/parties/[id]/summons/[summonId] - Update summon in party
@ -17,7 +17,7 @@ export const PUT: RequestHandler = async ({ request, params, fetch }) => {
}
// Forward to Rails API
const response = await fetch(buildUrl(`/grid_summons/${params.summonId}`), {
const response = await fetch(buildApiUrl(`/grid_summons/${params.summonId}`), {
method: 'PUT',
headers: {
'Content-Type': 'application/json',

View file

@ -1,5 +1,5 @@
import { json, type RequestHandler } from '@sveltejs/kit'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../../_utils'
/**
* POST /api/parties/[id]/weapons - Add weapon to party
@ -26,7 +26,7 @@ export const POST: RequestHandler = async ({ request, params, fetch }) => {
}
// Forward to Rails API
const response = await fetch(buildUrl('/weapons'), {
const response = await fetch(buildApiUrl('/weapons'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@ -38,7 +38,7 @@ export const POST: RequestHandler = async ({ request, params, fetch }) => {
const data = await response.json()
return json(data, { status: response.status })
} catch (error) {
console.error('Error adding weapon:', error)
return json(handleApiError(error, 'adding weapon'), { status: 500 })
return json(
{ error: 'Failed to add weapon' },
{ status: 500 }
@ -54,7 +54,7 @@ export const DELETE: RequestHandler = async ({ request, params, fetch }) => {
console.log('DELETE weapon request:', { body, params })
// Forward to Rails API - use grid_weapons endpoint with the ID
const response = await fetch(buildUrl(`/grid_weapons/${body.gridWeaponId}`), {
const response = await fetch(buildApiUrl(`/grid_weapons/${body.gridWeaponId}`), {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
@ -72,7 +72,7 @@ export const DELETE: RequestHandler = async ({ request, params, fetch }) => {
const errorData = await response.json().catch(() => ({}))
return json(errorData, { status: response.status })
} catch (error) {
console.error('Error removing weapon:', error)
return json(handleApiError(error, 'removing weapon'), { status: 500 })
return json(
{ error: 'Failed to remove weapon' },
{ status: 500 }

View file

@ -1,5 +1,5 @@
import { json, type RequestHandler } from '@sveltejs/kit'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../../../_utils'
/**
* PUT /api/parties/[id]/weapons/[weaponId] - Update weapon in party
@ -17,7 +17,7 @@ export const PUT: RequestHandler = async ({ request, params, fetch }) => {
}
// Forward to Rails API
const response = await fetch(buildUrl(`/grid_weapons/${params.weaponId}`), {
const response = await fetch(buildApiUrl(`/grid_weapons/${params.weaponId}`), {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
@ -29,7 +29,7 @@ export const PUT: RequestHandler = async ({ request, params, fetch }) => {
const data = await response.json()
return json(data, { status: response.status })
} catch (error) {
console.error('Error updating weapon:', error)
return json(handleApiError(error, 'updating weapon'), { status: 500 })
return json(
{ error: 'Failed to update weapon' },
{ status: 500 }

View file

@ -1,5 +1,5 @@
import { json, type RequestHandler } from '@sveltejs/kit'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../_utils'
export const POST: RequestHandler = async ({ request, fetch }) => {
try {
@ -7,7 +7,7 @@ export const POST: RequestHandler = async ({ request, fetch }) => {
const editKey = request.headers.get('X-Edit-Key')
// Forward to Rails API with automatic auth via handleFetch
const response = await fetch(buildUrl('/characters/update_uncap'), {
const response = await fetch(buildApiUrl('/characters/update_uncap'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',

View file

@ -1,5 +1,5 @@
import { json, type RequestHandler } from '@sveltejs/kit'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../_utils'
export const POST: RequestHandler = async ({ request, fetch }) => {
try {
@ -7,7 +7,7 @@ export const POST: RequestHandler = async ({ request, fetch }) => {
const editKey = request.headers.get('X-Edit-Key')
// Forward to Rails API with automatic auth via handleFetch
const response = await fetch(buildUrl('/summons/update_uncap'), {
const response = await fetch(buildApiUrl('/summons/update_uncap'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',

View file

@ -1,5 +1,5 @@
import { json, type RequestHandler } from '@sveltejs/kit'
import { buildUrl } from '$lib/api/core'
import { buildApiUrl, extractHeaders, handleApiError } from '../../_utils'
export const POST: RequestHandler = async ({ request, fetch }) => {
try {
@ -7,7 +7,7 @@ export const POST: RequestHandler = async ({ request, fetch }) => {
const editKey = request.headers.get('X-Edit-Key')
// Forward to Rails API with automatic auth via handleFetch
const response = await fetch(buildUrl('/weapons/update_uncap'), {
const response = await fetch(buildApiUrl('/weapons/update_uncap'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',