|
| 1 | +# Client API Layer Conventions |
| 2 | + |
| 3 | +This document explains how the client's API layer is structured, how errors are handled, and how to add a new server call end-to-end. |
| 4 | + |
| 5 | +--- |
| 6 | + |
| 7 | +## Folder structure |
| 8 | + |
| 9 | +All API service files live in `src/services/`: |
| 10 | + |
| 11 | +``` |
| 12 | +src/services/ |
| 13 | +├── api.service.ts # Base class — all services extend this |
| 14 | +├── auth.service.ts # Authentication endpoints |
| 15 | +└── course.service.ts # Creator / course data endpoints |
| 16 | +``` |
| 17 | + |
| 18 | +Each file exports a **singleton instance** of its service class. |
| 19 | + |
| 20 | +--- |
| 21 | + |
| 22 | +## File and class naming convention |
| 23 | + |
| 24 | +| What | Convention | Example | |
| 25 | +|---|---|---| |
| 26 | +| File name | `<domain>.service.ts` | `wallet.service.ts` | |
| 27 | +| Class name | `<Domain>Service` | `WalletService` | |
| 28 | +| Exported singleton | `<domain>Service` | `walletService` | |
| 29 | + |
| 30 | +Every service class **extends `BaseApiService`** from `api.service.ts`, which provides: |
| 31 | + |
| 32 | +- A pre-configured Axios instance (`this.api`) pointing at `VITE_BACKEND_URL` |
| 33 | +- Automatic token refresh on `401 TOKEN_EXPIRED` responses |
| 34 | +- A shared `handleError(error)` method that normalises any thrown value to `ApiError` |
| 35 | + |
| 36 | +--- |
| 37 | + |
| 38 | +## Error handling |
| 39 | + |
| 40 | +Every service method wraps its Axios call in a `try/catch` and re-throws via `this.handleError`: |
| 41 | + |
| 42 | +```ts |
| 43 | +async getWalletHoldings(address: string): Promise<Holding[]> { |
| 44 | + try { |
| 45 | + const response = await this.api.get<APIResponse<Holding[]>>( |
| 46 | + `/wallets/${address}/holdings` |
| 47 | + ); |
| 48 | + return response.data.data; |
| 49 | + } catch (error) { |
| 50 | + throw this.handleError(error); |
| 51 | + } |
| 52 | +} |
| 53 | +``` |
| 54 | + |
| 55 | +`handleError` always returns an `ApiError` instance with: |
| 56 | + |
| 57 | +| Field | Type | Description | |
| 58 | +|---|---|---| |
| 59 | +| `message` | `string` | Human-readable error message | |
| 60 | +| `status` | `number` | HTTP status code; `0` for network failures | |
| 61 | +| `response` | `APIErrorResponse \| undefined` | Full server error payload when available | |
| 62 | + |
| 63 | +Callers can check `error instanceof ApiError` and inspect `error.status` for branching logic. |
| 64 | + |
| 65 | +--- |
| 66 | + |
| 67 | +## How to add a new endpoint |
| 68 | + |
| 69 | +### 1. Add the method to the relevant service file |
| 70 | + |
| 71 | +Open `src/services/<domain>.service.ts` (or create a new one if the domain is new). Add a method that: |
| 72 | + |
| 73 | +1. Calls `this.api.get/post/patch/delete` |
| 74 | +2. Extracts `response.data.data` |
| 75 | +3. Re-throws any error via `this.handleError` |
| 76 | + |
| 77 | +```ts |
| 78 | +// src/services/wallet.service.ts |
| 79 | +import { BaseApiService, type APIResponse } from './api.service'; |
| 80 | + |
| 81 | +export interface Holding { |
| 82 | + creatorId: string; |
| 83 | + quantity: number; |
| 84 | + priceStroops: number; |
| 85 | +} |
| 86 | + |
| 87 | +class WalletService extends BaseApiService { |
| 88 | + async getHoldings(address: string): Promise<Holding[]> { |
| 89 | + try { |
| 90 | + const response = await this.api.get<APIResponse<Holding[]>>( |
| 91 | + `/wallets/${address}/holdings` |
| 92 | + ); |
| 93 | + return response.data.data; |
| 94 | + } catch (error) { |
| 95 | + throw this.handleError(error); |
| 96 | + } |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +export const walletService = new WalletService(); |
| 101 | +``` |
| 102 | + |
| 103 | +### 2. Define a query key in `src/lib/queryKeys.ts` |
| 104 | + |
| 105 | +Add an entry for the new endpoint so all hooks that reference the same data use an identical cache key: |
| 106 | + |
| 107 | +```ts |
| 108 | +// src/lib/queryKeys.ts |
| 109 | +wallet: { |
| 110 | + holdings: (address: string) => ['wallet', address, 'holdings'] as const, |
| 111 | + // ... |
| 112 | +}, |
| 113 | +``` |
| 114 | + |
| 115 | +### 3. Write a React Query hook |
| 116 | + |
| 117 | +`QueryClientProvider` is already wired up in `src/providers/Web3Provider.tsx` — no setup changes needed. |
| 118 | + |
| 119 | +```ts |
| 120 | +// src/hooks/useWalletHoldings.ts |
| 121 | +import { useQuery } from '@tanstack/react-query'; |
| 122 | +import { walletService } from '@/services/wallet.service'; |
| 123 | +import { queryKeys } from '@/lib/queryKeys'; |
| 124 | + |
| 125 | +export function useWalletHoldings(address: string | undefined) { |
| 126 | + return useQuery({ |
| 127 | + queryKey: queryKeys.wallet.holdings(address ?? ''), |
| 128 | + queryFn: () => walletService.getHoldings(address!), |
| 129 | + enabled: Boolean(address), |
| 130 | + }); |
| 131 | +} |
| 132 | +``` |
| 133 | + |
| 134 | +### 4. Consume the hook in a component |
| 135 | + |
| 136 | +```tsx |
| 137 | +import { useWalletHoldings } from '@/hooks/useWalletHoldings'; |
| 138 | + |
| 139 | +function HoldingsList({ address }: { address: string }) { |
| 140 | + const { data: holdings, isLoading, error } = useWalletHoldings(address); |
| 141 | + |
| 142 | + if (isLoading) return <p>Loading…</p>; |
| 143 | + if (error) return <p>Failed to load holdings.</p>; |
| 144 | + |
| 145 | + return ( |
| 146 | + <ul> |
| 147 | + {holdings?.map(h => ( |
| 148 | + <li key={h.creatorId}> |
| 149 | + {h.creatorId} — {h.quantity} keys |
| 150 | + </li> |
| 151 | + ))} |
| 152 | + </ul> |
| 153 | + ); |
| 154 | +} |
| 155 | +``` |
| 156 | + |
| 157 | +--- |
| 158 | + |
| 159 | +## Worked example — full GET call |
| 160 | + |
| 161 | +The following shows a complete end-to-end flow for a `GET /wallets/:address/holdings` endpoint. |
| 162 | + |
| 163 | +### Service method |
| 164 | + |
| 165 | +```ts |
| 166 | +// src/services/wallet.service.ts |
| 167 | +import { BaseApiService, type APIResponse } from './api.service'; |
| 168 | + |
| 169 | +export interface Holding { |
| 170 | + creatorId: string; |
| 171 | + quantity: number; |
| 172 | + priceStroops: number; |
| 173 | +} |
| 174 | + |
| 175 | +class WalletService extends BaseApiService { |
| 176 | + async getHoldings(address: string): Promise<Holding[]> { |
| 177 | + try { |
| 178 | + const response = await this.api.get<APIResponse<Holding[]>>( |
| 179 | + `/wallets/${address}/holdings` |
| 180 | + ); |
| 181 | + return response.data.data; |
| 182 | + } catch (error) { |
| 183 | + throw this.handleError(error); |
| 184 | + } |
| 185 | + } |
| 186 | +} |
| 187 | + |
| 188 | +export const walletService = new WalletService(); |
| 189 | +``` |
| 190 | + |
| 191 | +### Query key |
| 192 | + |
| 193 | +```ts |
| 194 | +// src/lib/queryKeys.ts (existing file — add the entry) |
| 195 | +wallet: { |
| 196 | + holdings: (address: string) => ['wallet', address, 'holdings'] as const, |
| 197 | +}, |
| 198 | +``` |
| 199 | + |
| 200 | +### Hook |
| 201 | + |
| 202 | +```ts |
| 203 | +// src/hooks/useWalletHoldings.ts |
| 204 | +import { useQuery } from '@tanstack/react-query'; |
| 205 | +import { walletService } from '@/services/wallet.service'; |
| 206 | +import { queryKeys } from '@/lib/queryKeys'; |
| 207 | + |
| 208 | +export function useWalletHoldings(address: string | undefined) { |
| 209 | + return useQuery({ |
| 210 | + queryKey: queryKeys.wallet.holdings(address ?? ''), |
| 211 | + queryFn: () => walletService.getHoldings(address!), |
| 212 | + enabled: Boolean(address), |
| 213 | + }); |
| 214 | +} |
| 215 | +``` |
| 216 | + |
| 217 | +### Component |
| 218 | + |
| 219 | +```tsx |
| 220 | +// Usage in any component |
| 221 | +import { useAccount } from 'wagmi'; |
| 222 | +import { useWalletHoldings } from '@/hooks/useWalletHoldings'; |
| 223 | + |
| 224 | +function HoldingsSummary() { |
| 225 | + const { address } = useAccount(); |
| 226 | + const { data: holdings, isLoading, error } = useWalletHoldings(address); |
| 227 | + |
| 228 | + if (isLoading) return <p>Loading…</p>; |
| 229 | + if (error) return <p>Could not load holdings.</p>; |
| 230 | + if (!holdings?.length) return <p>No holdings yet.</p>; |
| 231 | + |
| 232 | + return ( |
| 233 | + <ul> |
| 234 | + {holdings.map(h => ( |
| 235 | + <li key={h.creatorId}> |
| 236 | + {h.creatorId} — {h.quantity} keys at {h.priceStroops} stroops |
| 237 | + </li> |
| 238 | + ))} |
| 239 | + </ul> |
| 240 | + ); |
| 241 | +} |
| 242 | +``` |
| 243 | + |
| 244 | +--- |
| 245 | + |
| 246 | +## Key files at a glance |
| 247 | + |
| 248 | +| File | Purpose | |
| 249 | +|---|---| |
| 250 | +| `src/services/api.service.ts` | `BaseApiService`, `ApiError`, `APIResponse` types | |
| 251 | +| `src/services/auth.service.ts` | Auth endpoints (login, register, profile) | |
| 252 | +| `src/services/course.service.ts` | Creator / course endpoints | |
| 253 | +| `src/lib/queryKeys.ts` | Centralised React Query key constants | |
| 254 | +| `src/providers/Web3Provider.tsx` | `QueryClientProvider` setup | |
0 commit comments