refactor(api): introduce defineApi + axios request layer

Replace ad-hoc fetch httpClient with api/request.ts (axios interceptors,
envelope unwrap, auth refresh) and defineApi-based resource modules.
Move session hydration into api/auth, sync both templates, and update docs.

Co-authored-by: zuiidea <zuiiidea@gmail.com>
This commit is contained in:
Cursor Agent
2026-10-18 03:48:28 +00:00
co-authored by zuiidea
parent 60ef2fe7f8
commit 8ab7ade30b
36 changed files with 1169 additions and 585 deletions
+10 -10
View File
@@ -1,25 +1,25 @@
---
## applyTo: "src/api/**/\*.ts,src/utils/http.ts,src/mocks/handlers/**/\*.ts,src/mocks/createHandler.ts"
description: "Use when editing API clients, schemas, HTTP behavior, response types, or MSW endpoint handlers. Keywords: api, http, schema, zod, handler, endpoint, auth, users."
applyTo: "src/api/**/*.ts,src/mocks/handlers/**/*.ts,src/mocks/createHandler.ts"
description: "Use when editing API clients, schemas, HTTP behavior, response types, or MSW endpoint handlers. Keywords: api, request, defineApi, schema, zod, handler, endpoint, auth, users."
---
# API Instructions
## Purpose
Maintain strict API contracts and consistent server/client mock behavior.
Maintain strict API contracts and a single call path: **schemas → `defineApi` resource modules → UI**. Transport lives in `src/api/request.ts` (axios + interceptors).
## Do
- Keep request/response shapes schema-driven and type-safe.
- Reuse endpoint constants and shared response helpers.
- Keep handler response envelope consistent (`code`, `data`, `message`).
- Ensure mock handlers reflect real API behavior and error semantics.
- Keep naming stable for endpoint keys and mutation/query keys.
- Define APIs with `defineApi` in `src/api/<resource>.ts` (`method` defaults to `GET`; use `params` / `query` / `body` + `output`).
- Keep Zod schemas in `src/api/schemas.ts` as the single contract; parse inputs/outputs inside `defineApi`.
- Keep MSW handler envelopes consistent (`code`, `data`, `message`) and aligned with schemas.
- Co-locate React Query keys with resource modules (e.g. `userQueryKeys`).
- Use `hydrateSession` from `@/api/auth` after login/register or when restoring a session.
## Do Not
- Do not call `axios` or `@/api/request` transport helpers from routes/components — import resource functions only (`listUsers`, `login`, …).
- Do not return ad-hoc response shapes for one-off convenience.
- Do not bypass schema parsing in new client mutations/queries.
- Do not mix unrelated domain endpoints in the same module.