Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 8 additions & 9 deletions apps/web/src/app/meters/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { WalletGate } from '@/components/wallet-gate'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { PlusCircle, ShieldOff } from 'lucide-react'
import { CopyableText } from '@/components/copy-button'
import { useToast } from '@/components/ToastProvider'
import { apiFetch } from '@/lib/api-error'

interface Meter {
id: string
Expand All @@ -19,8 +21,7 @@ interface Meter {
}

async function fetchMeters(): Promise<Meter[]> {
const res = await fetch('/api/meters')
if (!res.ok) throw new Error('Failed to load meters')
const res = await apiFetch('/api/meters')
return res.json()
}

Expand All @@ -31,21 +32,16 @@ async function registerMeter(body: {
meter_group?: string
tags?: string[]
}): Promise<Meter> {
const res = await fetch('/api/meters', {
const res = await apiFetch('/api/meters', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (!res.ok) {
const err = await res.json().catch(() => ({}))
throw new Error(err.error ?? 'Registration failed')
}
return res.json()
}

async function revokeMeter(id: string): Promise<void> {
const res = await fetch(`/api/meters/${id}/revoke`, { method: 'PATCH' })
if (!res.ok) throw new Error('Revoke failed')
await apiFetch(`/api/meters/${id}/revoke`, { method: 'PATCH' })
}

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -441,6 +437,7 @@ function RevokeDialog({
// ---------------------------------------------------------------------------
export default function MetersPage() {
const qc = useQueryClient()
const { pushToast } = useToast()
const [revokeTarget, setRevokeTarget] = useState<Meter | null>(null)

const { data: meters, isLoading, error } = useQuery({
Expand All @@ -453,7 +450,9 @@ export default function MetersPage() {
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['meters'] })
setRevokeTarget(null)
pushToast({ variant: 'success', title: 'Meter revoked', description: 'The meter has been deactivated.' })
},
onError: (err: Error) => pushToast({ variant: 'error', title: 'Revoke failed', description: err.message }),
})

return (
Expand Down
40 changes: 40 additions & 0 deletions apps/web/src/lib/api-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
'use client'

/**
* Utility for consistent API error handling across pages.
*
* Parses the API error response body (supports both `{ error }` and
* `{ error, code, retriable }` shapes from AppError) and returns a
* normalised message plus optional retry guidance.
*/
export function parseApiError(errBody: unknown): string {
if (!errBody || typeof errBody !== 'object') return 'An unexpected error occurred.'
const body = errBody as Record<string, unknown>
const base = typeof body.error === 'string' ? body.error : 'An unexpected error occurred.'
if (body.retriable === true) {
return `${base} Please try again.`
}
if (body.code === 'STELLAR_CIRCUIT' || body.code === 'STELLAR_TIMEOUT') {
return `${base} The Stellar network is temporarily unavailable — please try again in a few moments.`
}
return base
}

/**
* Fetch wrapper that throws a normalised error string on non-ok responses.
* Use in combination with `useToast` to surface errors consistently.
*
* @example
* const data = await apiFetch('/api/certificates').catch(msg => {
* pushToast({ variant: 'error', title: 'Load failed', description: msg })
* throw msg
* })
*/
export async function apiFetch(input: RequestInfo, init?: RequestInit): Promise<Response> {
const res = await fetch(input, init)
if (!res.ok) {
const body = await res.json().catch(() => ({}))
throw new Error(parseApiError(body))
}
return res
}
Loading