mirror of
https://github.com/sunniejs/vue-h5-template.git
synced 2026-11-28 02:43:34 +08:00
docs: document favorites, chat suggestions and integration boundaries
This commit is contained in:
parent
e94b85de04
commit
4bd7f919fb
@ -37,3 +37,19 @@ Markdown-it disables raw HTML, then DOMPurify removes script, iframe, form, styl
|
||||
## Mobile Behavior
|
||||
|
||||
VisualViewport tracks the software keyboard, the composer includes safe-area padding, the textarea auto-grows, and a Scroll To Bottom control appears when the user reads older messages without forcing scroll position.
|
||||
|
||||
## Localized starter prompts
|
||||
|
||||
The chat empty state loads `GET /api/ai/suggestions` as a JSON request. The query is separated by language, remains fresh for five minutes, and disables automatic retries. While loading, on an empty result, or after failure, translated local prompts remain usable. Selecting a prompt follows the existing send/stop flow; this request does not change the SSE protocol or persist a conversation.
|
||||
|
||||
The client maps `zh-*` to `zh-CN`, `ja-*` to `ja-JP`, and other languages to `en-US`. FastAPI itself only accepts those three exact values; omission defaults to `en-US`, and unsupported values return HTTP 422. The explicit `locale` query parameter selects the prompts; do not rely on `Accept-Language` alone.
|
||||
|
||||
The single app uses `VITE_AI_API_BASE_URL` (default `/api/ai`) for suggestions and `VITE_AI_API_TARGET` for the development proxy. Business traffic uses the Gin target. `src/api/modules/ai.ts` owns this JSON call; streaming stays in the provider/composable.
|
||||
|
||||
```ts
|
||||
import { getChatSuggestions } from '@/api/modules/ai';
|
||||
|
||||
const prompts = await getChatSuggestions(locale, signal, '/api/ai');
|
||||
```
|
||||
|
||||
[API](./request.md) · [Tests](./testing.md)
|
||||
|
||||
@ -1,38 +1,42 @@
|
||||
# Backend Services and Local Integration
|
||||
# Backend integration
|
||||
|
||||
## Why there are two repositories
|
||||
The business service runs Go/Gin on 8002 and owns authentication, products and favorites; FastAPI runs on 8001 and owns AI JSON/SSE. Start each service using its own quick-start instructions, then run the frontend with the committed `.env.integration`:
|
||||
|
||||
Backend workloads are split by runtime and scaling profile:
|
||||
|
||||
- `vue-h5-template-business-service`: Gin + PostgreSQL for login, profiles, projects, and product CRUD.
|
||||
- `vue-h5-template-ai-service`: FastAPI + Redis for AI providers, authenticated SSE, and quotas.
|
||||
|
||||
Their languages, dependencies, CI, and release cycles differ. They share a JWT contract but no source imports. The parent backend directory is local Compose orchestration, not a third repository. Each backend repository has Chinese, English, and Japanese guides on its `docs` branch.
|
||||
|
||||
## Start the complete stack
|
||||
```text
|
||||
VITE_USE_MOCK=false
|
||||
VITE_API_BASE_URL=/api
|
||||
VITE_AI_API_BASE_URL=/api/ai
|
||||
VITE_API_TARGET=http://127.0.0.1:8002
|
||||
VITE_AI_API_TARGET=http://127.0.0.1:8001
|
||||
VITE_REQUEST_ID_ENABLED=true
|
||||
VITE_PWA_ENABLED=false
|
||||
```
|
||||
|
||||
```bash
|
||||
cd /Users/fong/Workspace/personal/backend/vue-h5-template
|
||||
docker compose up --build -d
|
||||
docker compose ps
|
||||
|
||||
cd /Users/fong/Workspace/personal/frontend/vue/vue-h5-template/vue-h5-template
|
||||
pnpm install
|
||||
pnpm dev:integration
|
||||
```
|
||||
|
||||
Open the URL printed by Vite and sign in with `demo` / `demo1234`. `/shop` is public, `/shop/admin/products` provides authenticated administration, and `/ai/chat` streams through FastAPI.
|
||||
## Contract differences to resolve
|
||||
|
||||
The Vite proxy forwards requests; it does not translate API contracts. Before treating a full browser flow as integrated, reconcile these differences:
|
||||
|
||||
- Login: frontend sends `name` and reads `token`; Gin expects `username` and returns `accessToken`.
|
||||
- Profile: frontend requests `/api/user/profile`; Gin exposes `/api/user/info`.
|
||||
- Catalog: frontend requests `/api/products` and `/api/products/:id`, using localized `name` and `priceCents`; Gin exposes `/api/product/list` and `/api/product/detail?id=…`, returning `title` and `price`.
|
||||
- Project CRUD exists in the frontend contract, but the current Gin router does not register Project endpoints.
|
||||
|
||||
## New feature boundaries
|
||||
|
||||
The favorite GET/POST paths match Gin, but require a Gin-issued JWT and an existing public product ID. A frontend Mock token is not valid for the real services. AI suggestions are public JSON and can be checked independently of login. The browser session cannot be assumed integrated simply because the transport accepts the service envelope.
|
||||
|
||||
## Verification
|
||||
|
||||
Use API-level checks below before browser integration. Obtain `BUSINESS_USER_JWT` from the business service’s actual login response; use its development account configuration, not old documentation credentials. Browser E2E against Mock does not establish real database or cross-service integration.
|
||||
|
||||
```bash
|
||||
cd /Users/fong/Workspace/personal/backend/vue-h5-template
|
||||
SMOKE_BASE_URL=http://127.0.0.1:5173 python3 scripts/smoke.py
|
||||
curl -s 'http://127.0.0.1:8001/api/ai/suggestions?locale=ja-JP'
|
||||
curl -s 'http://127.0.0.1:8002/api/product/favorite?id=1' \
|
||||
-H "Authorization: Bearer $BUSINESS_USER_JWT"
|
||||
```
|
||||
|
||||
The smoke test verifies the Vue proxy, Gin login and product CRUD, PostgreSQL persistence, and authenticated FastAPI streaming, then removes temporary records.
|
||||
|
||||
## PostgreSQL and DataGrip
|
||||
|
||||
Compose exposes PostgreSQL 17 on `localhost:5432`, database `vue_h5_business`, user `vue_h5`, password `vue_h5_local`. Create a PostgreSQL DataGrip source and install the official JDBC driver when prompted. Inspect `products`, `users`, `projects`, and `schema_migrations`. These credentials are local-only and must be replaced in production.
|
||||
|
||||
`docker compose stop` or `docker compose down` preserves the database volume. Run `docker compose down -v` only when you intentionally want irreversible local data removal.
|
||||
|
||||
[API](./request.md) · [AI Chat](./ai-chat.md) · [Commerce](./commerce.md)
|
||||
|
||||
@ -16,5 +16,22 @@ Product contracts are generated from `openapi/schema.yaml`. Money is stored as i
|
||||
|
||||
Cover images allow same-origin paths or HTTPS only and fall back to a local placeholder. Admin deletion is soft deletion and the public API exposes only `on_sale` products.
|
||||
|
||||
`pnpm dev` uses `mock/index.ts`, so the full store works without Docker. `pnpm dev:integration` sends the same API module calls to Gin and persists data in PostgreSQL. Pages contain no environment-specific branches.
|
||||
`pnpm dev` uses `mock/index.ts`, so the full store works without Docker. `pnpm dev:integration` configures the Gin/FastAPI proxies. Review the contract differences below before using the full flow against these services.
|
||||
|
||||
## Favorite interaction
|
||||
|
||||
`FavoriteButton` receives a numeric `productId` and the current `session` token. Signed-out users see a login link; no private-state request is sent. A valid signed-in product loads its saved state before enabling the action. Failed reads offer retry. Failed writes preserve the last confirmed state and display an error. Fetching or saving disables duplicate submissions.
|
||||
|
||||
Favorite state belongs to TanStack Query. Cache keys include the control instance, session generation and product ID; they do not contain the token. A mutation captures its original cache key, so a late response cannot overwrite another account or product. Each new mount/session reads the server again. The action sets an explicit boolean rather than asking the server to invert unknown state.
|
||||
|
||||
```text
|
||||
GET /api/product/favorite?id=1
|
||||
POST /api/product/favorite
|
||||
{ "productId": 1, "favorite": true }
|
||||
```
|
||||
|
||||
`src/components/shop/FavoriteButton.vue` → `src/api/modules/favorites.ts` → `apiClient`.
|
||||
|
||||
Response-envelope compatibility does not adapt endpoint names or domain fields. This app’s catalog still uses `/api/products` and localized `name`/`priceCents`; the current Gin catalog exposes `/api/product/list` and `title`/`price`. Login also differs (`name`/`token` versus `username`/`accessToken`). Check the remaining contracts or add explicit domain adapters before claiming full integration. The new favorite paths match Gin; their authenticated use still requires a compatible issued JWT.
|
||||
|
||||
[API](./request.md) · [Tests](./testing.md)
|
||||
|
||||
@ -20,7 +20,7 @@ Pages do not import Axios. Module functions own URLs, parameters, and result typ
|
||||
|
||||
The request interceptor adds a Bearer token and `X-Request-ID` when configured. The response interceptor separates business and HTTP failures. A runtime 401 handler clears the session and navigates without importing Router into the client.
|
||||
|
||||
`src/api/modules/projects.ts` is the real Gin CRUD example. `/examples/projects` uses TanStack Query for its paginated list and mutations, so the page never stores server state. The envelope accepts the full successful 2xx range, allowing an HTTP 201 create response to unwrap normally.
|
||||
`src/api/modules/projects.ts` defines the frontend project CRUD contract; the current Gin router does not register Project endpoints. `/examples/workspace` uses TanStack Query for its paginated list and mutations, so the page never stores server state. The envelope accepts the full successful 2xx range, allowing an HTTP 201 create response to unwrap normally.
|
||||
|
||||
## OpenAPI
|
||||
|
||||
@ -35,3 +35,13 @@ Output is written to `src/types/api/generated.d.ts`. Replace the schema or comma
|
||||
## Security
|
||||
|
||||
`VITE_*` values ship to the browser; never put keys there. The example token uses `sessionStorage`; production should prefer SameSite, Secure, HttpOnly cookies and a BFF. Redirects accept only same-origin absolute paths beginning with a single `/`.
|
||||
|
||||
## REST contracts and cancellation
|
||||
|
||||
The single-app transport accepts service envelopes with `code: 0` and `message`, as well as legacy Mock envelopes with a 2xx business code and `msg`. Both unwrap `data`; failures remain `ApiError`. HTTP 2xx alone is not enough to establish business success.
|
||||
|
||||
These helpers return unwrapped data and reject through `ApiError`. Forward the query’s `AbortSignal` to reads. A favorite write uses the authenticated client configured at bootstrap; never send a caller-supplied owner ID.
|
||||
|
||||
The single app uses `VITE_AI_API_BASE_URL` (default `/api/ai`) for suggestions and `VITE_AI_API_TARGET` for the development proxy. Business traffic uses the Gin target. `src/api/modules/ai.ts` owns this JSON call; streaming stays in the provider/composable.
|
||||
|
||||
Response-envelope compatibility does not adapt endpoint names or domain fields. This app’s catalog still uses `/api/products` and localized `name`/`priceCents`; the current Gin catalog exposes `/api/product/list` and `title`/`price`. Login also differs (`name`/`token` versus `username`/`accessToken`). Check the remaining contracts or add explicit domain adapters before claiming full integration. The new favorite paths match Gin; their authenticated use still requires a compatible issued JWT.
|
||||
|
||||
@ -16,9 +16,9 @@ pnpm check
|
||||
|
||||
## Current Coverage
|
||||
|
||||
Vitest and Vue Test Utils cover URL redirects, request errors, API modules, the user store, SSE parsing, the streaming composable, safe Markdown, Login Form, and Chat Composer. Core thresholds are 60% for lines/statements/functions and 50% branches; v2 currently reports 76.68% lines.
|
||||
Vitest and Vue Test Utils cover URL redirects, request errors, API modules, the user store, SSE parsing, the streaming composable, safe Markdown, Login Form, and Chat Composer. Core thresholds are 60% for lines/statements/functions and 50% branches; Run `pnpm test:coverage` for the current result; this is not whole-application coverage.
|
||||
|
||||
Playwright uses a Pixel 7 profile for Home, three-language switching, the shop catalog/detail flow, empty Login privacy checks, Mock API, AI Streaming/Stop, and 401 Redirect. The backend workspace adds `scripts/smoke.py`, which verifies Gin login/product CRUD, PostgreSQL, and authenticated FastAPI SSE through the real Vue proxy.
|
||||
Playwright uses a Pixel 7 profile for Home, three-language switching, the shop catalog/detail flow, empty Login privacy checks, Mock API, AI Streaming/Stop, and 401 Redirect. Real-service verification requires reconciling the login/catalog contracts and configuring the database and AI environments. Mock E2E does not establish that integration.
|
||||
|
||||
Backend gates are Ruff + mypy + pytest for FastAPI and `go test ./...` + `go vet ./...` for Gin. The backend workspace includes its own GitHub Actions workflow.
|
||||
|
||||
@ -27,3 +27,17 @@ Backend gates are Ruff + mypy + pytest for FastAPI and `go test ./...` + `go vet
|
||||
Test public behavior, not trivial getters or static copy. Protocol parsing, auth, errors, and cancellation are high-risk shared logic and require unit tests. Route, mock, login, and streaming critical paths require E2E coverage.
|
||||
|
||||
GitHub Actions uses the pnpm cache, installs dependencies once, runs `check`, installs Chromium, then runs E2E.
|
||||
|
||||
## Feature regression checks
|
||||
|
||||
API tests cover ID/body forwarding, cancellation, locale normalization, the AI base URL and rejected requests. Favorite component tests cover signed-out access, save/remove, read retry, failed writes and a late write after an account switch. Streaming composable tests cover stop, cancellation and overlapping lifecycles; browser tests below validate remote prompts and fallback. Each test uses an isolated QueryClient and clears it after use.
|
||||
|
||||
```bash
|
||||
pnpm test tests/api/features.test.ts tests/api/client.test.ts tests/components/FavoriteButton.test.ts
|
||||
pnpm test:coverage
|
||||
pnpm test:e2e
|
||||
```
|
||||
|
||||
Playwright checks that a favorite survives a browser reload, can be removed, and that chat uses remote suggestions then falls back on a failed request. Keep streaming tests independent of suggestion copy by submitting a typed prompt. These are development-Mock checks; PostgreSQL/Redis integration needs its own configured environment.
|
||||
|
||||
Run the application test commands from the application checkout, not this `docs` branch. The documentation checkout only runs `pnpm build` to validate VitePress. Use current command output as verification evidence.
|
||||
|
||||
@ -37,3 +37,19 @@ Markdown-it 禁止 raw HTML,渲染结果再由 DOMPurify 移除脚本、iframe
|
||||
## 移动端
|
||||
|
||||
页面使用 VisualViewport 跟随软键盘高度,输入栏包含 safe-area,textarea 自动增高,用户离开底部时显示 Scroll To Bottom,且不会强制抢回滚动位置。
|
||||
|
||||
## 按语言加载聊天建议
|
||||
|
||||
聊天空状态通过 JSON 请求加载 `GET /api/ai/suggestions`。Query 按语言区分,五分钟内视为新鲜数据,不自动重试。加载中、结果为空或请求失败时继续显示本地翻译建议。点击建议仍走原有发送与停止流程,不改变 SSE 协议,也不保存会话历史。
|
||||
|
||||
客户端把 `zh-*` 映射为 `zh-CN`、`ja-*` 映射为 `ja-JP`,其他语言映射为 `en-US`。FastAPI 本身只接受这三个精确值,省略时默认 `en-US`,非法值返回 HTTP 422。语言由显式 `locale` 查询参数决定,不能只依赖 `Accept-Language`。
|
||||
|
||||
单应用通过 `VITE_AI_API_BASE_URL`(默认 `/api/ai`)请求建议,通过 `VITE_AI_API_TARGET` 配置开发代理;常规业务请求发往 Gin。JSON 请求位于 `src/api/modules/ai.ts`,流式协议仍由 Provider/composable 管理。
|
||||
|
||||
```ts
|
||||
import { getChatSuggestions } from '@/api/modules/ai';
|
||||
|
||||
const prompts = await getChatSuggestions(locale, signal, '/api/ai');
|
||||
```
|
||||
|
||||
[API](./request.md) · [测试](./testing.md)
|
||||
|
||||
@ -1,57 +1,42 @@
|
||||
# 后端服务与本地联调
|
||||
# 后端服务与联调
|
||||
|
||||
## 为什么拆成两个仓库
|
||||
Go/Gin 业务服务监听 8002,负责认证、商品与收藏;FastAPI 监听 8001,负责 AI JSON/SSE。先按两个服务各自的快速开始启动,再使用已提交的 `.env.integration`:
|
||||
|
||||
后端按运行时和扩缩容特征拆分,适合分别发布到 GitHub:
|
||||
|
||||
- `vue-h5-template-business-service`:Gin + PostgreSQL,负责登录、用户、Project 与商品 CRUD。
|
||||
- `vue-h5-template-ai-service`:FastAPI + Redis,负责 AI Provider、鉴权 SSE 和限流。
|
||||
|
||||
两者语言、依赖、CI 和部署节奏不同。它们只共享 JWT 协议,不应互相导入代码。上层 `vue-h5-template` 目录仅作为本地 Compose 编排,不需要成为第三个仓库。两个后端仓库的 `docs` 分支均有中、英、日开发文档。
|
||||
|
||||
## 启动完整环境
|
||||
```text
|
||||
VITE_USE_MOCK=false
|
||||
VITE_API_BASE_URL=/api
|
||||
VITE_AI_API_BASE_URL=/api/ai
|
||||
VITE_API_TARGET=http://127.0.0.1:8002
|
||||
VITE_AI_API_TARGET=http://127.0.0.1:8001
|
||||
VITE_REQUEST_ID_ENABLED=true
|
||||
VITE_PWA_ENABLED=false
|
||||
```
|
||||
|
||||
```bash
|
||||
cd /Users/fong/Workspace/personal/backend/vue-h5-template
|
||||
docker compose up --build -d
|
||||
docker compose ps
|
||||
|
||||
cd /Users/fong/Workspace/personal/frontend/vue/vue-h5-template/vue-h5-template
|
||||
pnpm install
|
||||
pnpm dev:integration
|
||||
```
|
||||
|
||||
打开终端输出的地址,使用演示账号 `demo` / `demo1234`。`/shop` 是公开商城;登录后可进入 `/shop/admin/products`;`/ai/chat` 使用 FastAPI SSE。
|
||||
## 需要先对齐的契约
|
||||
|
||||
端到端检查:
|
||||
Vite 代理只转发请求,不转换接口契约。当前完整页面链路仍需对齐以下差异:
|
||||
|
||||
- 登录:前端提交 `name`、读取 `token`;Gin 接收 `username`、返回 `accessToken`。
|
||||
- 用户:前端请求 `/api/user/profile`;Gin 提供 `/api/user/info`。
|
||||
- 商品:前端使用 `/api/products`、`/api/products/:id` 与多语言 `name`、`priceCents`;Gin 使用 `/api/product/list`、`/api/product/detail?id=…` 与 `title`、`price`。
|
||||
- 前端契约包含 Project CRUD,当前 Gin Router 未注册对应路由。
|
||||
|
||||
## 新增功能的边界
|
||||
|
||||
新增收藏 GET/POST 路径与 Gin 一致,但需要 Gin 签发的 JWT 和已存在的公开商品 ID;前端 Mock Token 不能用于真实服务。AI 建议是公开 JSON 接口,可独立于登录验证。请求客户端接受真实服务响应包装,不代表完整用户会话已联通。
|
||||
|
||||
## 验证方式
|
||||
|
||||
先执行下面的接口检查,再做浏览器联调。`BUSINESS_USER_JWT` 应来自业务服务实际登录响应,账号以该服务开发配置为准,不沿用旧文档凭证。Mock E2E 通过不能证明真实数据库与双服务联调已通过。
|
||||
|
||||
```bash
|
||||
cd /Users/fong/Workspace/personal/backend/vue-h5-template
|
||||
SMOKE_BASE_URL=http://127.0.0.1:5173 python3 scripts/smoke.py
|
||||
curl -s 'http://127.0.0.1:8001/api/ai/suggestions?locale=ja-JP'
|
||||
curl -s 'http://127.0.0.1:8002/api/product/favorite?id=1' \
|
||||
-H "Authorization: Bearer $BUSINESS_USER_JWT"
|
||||
```
|
||||
|
||||
脚本验证 Vue 代理、Gin 登录与商品 CRUD、PostgreSQL 持久化,以及 FastAPI 鉴权 Streaming,并清理临时记录。
|
||||
|
||||
## PostgreSQL 与 DataGrip
|
||||
|
||||
Compose 默认启动 PostgreSQL 17,数据库连接是:
|
||||
|
||||
```text
|
||||
Host: localhost
|
||||
Port: 5432
|
||||
Database: vue_h5_business
|
||||
User: vue_h5
|
||||
Password: vue_h5_local
|
||||
```
|
||||
|
||||
在 DataGrip 新建 PostgreSQL 数据源并下载官方 JDBC Driver。通过 Schemas 面板可以查看 `products`、`users`、`projects` 和 `schema_migrations`。这些密码仅用于本地 Compose,生产必须更换。
|
||||
|
||||
## 停止与数据
|
||||
|
||||
```bash
|
||||
docker compose stop
|
||||
docker compose down
|
||||
```
|
||||
|
||||
上述命令不会删除 PostgreSQL Volume。只有明确需要清空本地数据时才执行 `docker compose down -v`,该操作不可恢复。
|
||||
|
||||
[API](./request.md) · [AI Chat](./ai-chat.md) · [Commerce](./commerce.md)
|
||||
|
||||
@ -18,5 +18,22 @@
|
||||
|
||||
## Mock 与真实后端
|
||||
|
||||
`pnpm dev` 使用 `mock/index.ts`,无需 Docker 即可浏览和编辑商品。`pnpm dev:integration` 把同一套 API 调用转发到 Gin,数据保存到 PostgreSQL。页面代码不包含环境条件分支。
|
||||
`pnpm dev` 使用 `mock/index.ts`,无需 Docker 即可浏览和编辑商品。`pnpm dev:integration` 配置 Gin/FastAPI 代理。启用代理不代表所有旧业务契约已匹配,见下方接入边界。
|
||||
|
||||
## 收藏交互与会话隔离
|
||||
|
||||
`FavoriteButton` 接收数值 `productId` 和当前 `session` Token。未登录时显示登录链接,不请求私有状态;登录后先读取已保存的状态,再启用操作。读取失败可重试,写入失败保留最后确认的状态并提示错误。读取和保存期间禁用重复提交。
|
||||
|
||||
收藏状态由 TanStack Query 管理。缓存键包含控件实例、会话代数和商品 ID,不包含 Token。Mutation 捕获提交时的缓存键,旧响应只更新原来的缓存,不能覆盖另一个账号或商品。重新挂载、切换会话后重新读取服务端。操作提交明确的布尔值,不让服务端反转一个未知状态。
|
||||
|
||||
```text
|
||||
GET /api/product/favorite?id=1
|
||||
POST /api/product/favorite
|
||||
{ "productId": 1, "favorite": true }
|
||||
```
|
||||
|
||||
`src/components/shop/FavoriteButton.vue` → `src/api/modules/favorites.ts` → `apiClient`.
|
||||
|
||||
响应包装兼容不会自动转换路径或业务字段。单应用商品模块仍使用 `/api/products` 与多语言 `name`/`priceCents`,当前 Gin 商品接口为 `/api/product/list` 与 `title`/`price`;登录也存在 `name`/`token` 与 `username`/`accessToken` 的差异。完整联调前需要核对其余契约或增加明确的领域适配。新增收藏路径已与 Gin 对齐,但鉴权仍需要兼容的已签发 JWT。
|
||||
|
||||
[API](./request.md) · [测试](./testing.md)
|
||||
|
||||
@ -20,7 +20,7 @@ View / Query composable
|
||||
|
||||
请求拦截器按需加入 Bearer Token 和 `X-Request-ID`。响应拦截器区分业务错误与 HTTP 错误;401 通过运行时 handler 清理会话并跳转,不让 client 直接导入 Router。
|
||||
|
||||
`src/api/modules/projects.ts` 是真实 Gin CRUD 示例。`/examples/projects` 使用 TanStack Query 管理分页列表和 Mutation,页面不保存 Server State。统一响应的 `code` 接受整个 2xx 区间,因此 HTTP 201 创建响应仍能正确解包。
|
||||
`src/api/modules/projects.ts` 定义项目 CRUD 的前端契约;当前 Gin 未注册对应 Project 路由。`/examples/workspace` 使用 TanStack Query 管理分页列表和 Mutation,页面不保存 Server State。统一响应的 `code` 接受整个 2xx 区间,因此 HTTP 201 创建响应仍能正确解包。
|
||||
|
||||
## OpenAPI
|
||||
|
||||
@ -35,3 +35,13 @@ pnpm api:generate
|
||||
## 安全
|
||||
|
||||
`VITE_*` 会进入浏览器产物,禁止放 API 密钥。示例 Token 使用 `sessionStorage`;生产优先使用 SameSite、Secure、HttpOnly Cookie/BFF。重定向只接受以单 `/` 开头的站内路径。
|
||||
|
||||
## REST 契约与请求取消
|
||||
|
||||
单应用请求客户端同时接受真实服务的 `code: 0`/`message` 和旧 Mock 的 2xx 业务码/`msg`,统一解包 `data`,失败仍为 `ApiError`。HTTP 2xx 不等于业务成功。
|
||||
|
||||
以下函数直接返回解包后的数据,并通过 `ApiError` 拒绝失败请求。读取操作应转发 Query 的 `AbortSignal`。收藏写入使用 bootstrap 统一配置的登录客户端,不接受调用方提供的用户 ID。
|
||||
|
||||
单应用通过 `VITE_AI_API_BASE_URL`(默认 `/api/ai`)请求建议,通过 `VITE_AI_API_TARGET` 配置开发代理;常规业务请求发往 Gin。JSON 请求位于 `src/api/modules/ai.ts`,流式协议仍由 Provider/composable 管理。
|
||||
|
||||
响应包装兼容不会自动转换路径或业务字段。单应用商品模块仍使用 `/api/products` 与多语言 `name`/`priceCents`,当前 Gin 商品接口为 `/api/product/list` 与 `title`/`price`;登录也存在 `name`/`token` 与 `username`/`accessToken` 的差异。完整联调前需要核对其余契约或增加明确的领域适配。新增收藏路径已与 Gin 对齐,但鉴权仍需要兼容的已签发 JWT。
|
||||
|
||||
@ -16,9 +16,9 @@ pnpm check
|
||||
|
||||
## 当前覆盖
|
||||
|
||||
Vitest + Vue Test Utils 覆盖 URL/Redirect、请求错误、API modules、user Store、SSE parser、streaming composable、安全 Markdown、Login Form 和 Chat Composer。核心范围门槛为 lines/statements/functions 60%,branches 50%;v2 实测 lines 76.68%。
|
||||
Vitest + Vue Test Utils 覆盖 URL/Redirect、请求错误、API modules、user Store、SSE parser、streaming composable、安全 Markdown、Login Form 和 Chat Composer。核心范围门槛为 lines/statements/functions 60%,branches 50%;具体覆盖率以当前 `pnpm test:coverage` 输出为准,不代表整个应用的覆盖率。
|
||||
|
||||
Playwright 使用 Pixel 7 配置覆盖 Home、三语言切换、商城列表与详情、Login 空值隐私检查、Mock API、AI Streaming/Stop 与 401 Redirect。后端工作区的 `scripts/smoke.py` 额外通过真实 Vue 代理验证 Gin 登录/商品 CRUD、PostgreSQL 和 FastAPI 鉴权 SSE。
|
||||
Playwright 使用 Pixel 7 配置覆盖 Home、三语言切换、商城列表与详情、Login 空值隐私检查、Mock API、AI Streaming/Stop 与 401 Redirect。真实服务验证需先完成登录/商品契约适配,再分别配置数据库与 AI 环境;Mock E2E 不能替代真实联调。
|
||||
|
||||
后端质量门禁分别为 FastAPI 的 Ruff + mypy + pytest,以及 Gin 的 `go test ./...` + `go vet ./...`。后端工作区自带独立 GitHub Actions 配置。
|
||||
|
||||
@ -27,3 +27,17 @@ Playwright 使用 Pixel 7 配置覆盖 Home、三语言切换、商城列表与
|
||||
测试公共行为,不测试无意义的 getter 或静态文案。协议解析、鉴权、错误和取消属于高风险公共逻辑;修改它们必须加单元测试。路由、Mock、登录和 Streaming 的关键链路必须有 E2E。
|
||||
|
||||
GitHub Actions 使用 pnpm cache,只安装一次依赖,先运行 `check`,再安装 Chromium 并运行 E2E。
|
||||
|
||||
## 新增功能回归检查
|
||||
|
||||
API 测试覆盖 ID、请求体、取消信号、语言归一化、AI base URL 和失败传递。收藏组件测试覆盖未登录、保存与取消、读取重试、写入失败及切换账号后的旧写入;流式 composable 测试覆盖停止、取消和并发生命周期;远程建议与本地回退由下方浏览器测试验证。每个测试独立创建并清理 QueryClient。
|
||||
|
||||
```bash
|
||||
pnpm test tests/api/features.test.ts tests/api/client.test.ts tests/components/FavoriteButton.test.ts
|
||||
pnpm test:coverage
|
||||
pnpm test:e2e
|
||||
```
|
||||
|
||||
Playwright 验证收藏刷新保持、取消收藏、远程建议以及请求失败后的本地回退。流式测试通过输入框提交固定问题,不依赖建议文案。以上属于开发 Mock 验证;PostgreSQL/Redis 集成需要单独配置环境。
|
||||
|
||||
以下应用测试命令应在应用分支的工作区执行,不能在本 `docs` 分支执行。文档工作区通过 `pnpm build` 验证 VitePress。验证结果应以当前命令输出为准。
|
||||
|
||||
@ -8,3 +8,18 @@ Markdown は Raw HTML を無効にし、DOMPurify で再度 Sanitization しま
|
||||
|
||||
FastAPI は Gin JWT を検証し、Redis でユーザー単位に制限します。Provider Key は Backend だけに保存します。
|
||||
|
||||
## 言語別の開始用プロンプト
|
||||
|
||||
チャットの空状態は JSON の `GET /api/ai/suggestions` を使います。言語別にキャッシュし、鮮度を五分間に設定して自動再試行を無効にしています。読み込み中、空の結果、通信失敗時には翻訳済みのローカル提案を使います。選択後は既存の送信・停止処理に進み、SSE 契約や会話の保存処理は変更しません。
|
||||
|
||||
クライアントは `zh-*` を `zh-CN`、`ja-*` を `ja-JP`、その他を `en-US` に変換します。FastAPI が受け付けるのはこの三つの値のみです。省略時は `en-US`、未対応の値は HTTP 422 です。言語は `locale` クエリで指定し、`Accept-Language` だけには依存しません。
|
||||
|
||||
単体アプリでは `VITE_AI_API_BASE_URL`(既定 `/api/ai`)で提案を取得し、開発プロキシを `VITE_AI_API_TARGET` で指定します。通常の業務通信は Gin に送ります。JSON は `src/api/modules/ai.ts`、ストリーミングはプロバイダーと composable が担当します。
|
||||
|
||||
```ts
|
||||
import { getChatSuggestions } from '@/api/modules/ai';
|
||||
|
||||
const prompts = await getChatSuggestions(locale, signal, '/api/ai');
|
||||
```
|
||||
|
||||
[API](./request.md) · [テスト](./testing.md)
|
||||
|
||||
@ -1,21 +1,42 @@
|
||||
# バックエンド連携
|
||||
|
||||
バックエンドは独立した2リポジトリです。
|
||||
Go/Gin の業務サービスは 8002 で認証・商品・お気に入りを担当し、FastAPI は 8001 で AI JSON/SSE を担当します。各サービスのクイックスタートで起動した後、登録済みの `.env.integration` を使います。
|
||||
|
||||
- `vue-h5-template-business-service`: Gin + PostgreSQL。認証、プロフィール、Project、商品 CRUD。
|
||||
- `vue-h5-template-ai-service`: FastAPI + Redis。AI Provider、認証付き SSE、レート制限。
|
||||
|
||||
親ディレクトリはローカル Compose 用で、第三の Git リポジトリにはしません。各サービスの `docs` ブランチにも中英日ガイドがあります。
|
||||
```text
|
||||
VITE_USE_MOCK=false
|
||||
VITE_API_BASE_URL=/api
|
||||
VITE_AI_API_BASE_URL=/api/ai
|
||||
VITE_API_TARGET=http://127.0.0.1:8002
|
||||
VITE_AI_API_TARGET=http://127.0.0.1:8001
|
||||
VITE_REQUEST_ID_ENABLED=true
|
||||
VITE_PWA_ENABLED=false
|
||||
```
|
||||
|
||||
```bash
|
||||
cd /Users/fong/Workspace/personal/backend/vue-h5-template
|
||||
docker compose up --build -d
|
||||
|
||||
cd /Users/fong/Workspace/personal/frontend/vue/vue-h5-template/vue-h5-template
|
||||
pnpm dev:integration
|
||||
```
|
||||
|
||||
デモアカウントは `demo` / `demo1234` です。DataGrip は Host `localhost`、Port `5432`、Database `vue_h5_business`、User `vue_h5`、Password `vue_h5_local` で接続できます。これはローカル専用です。
|
||||
## 先にそろえる API 契約
|
||||
|
||||
`SMOKE_BASE_URL=http://127.0.0.1:5173 python3 scripts/smoke.py` で Vue Proxy、Gin、PostgreSQL、FastAPI SSE をまとめて検証できます。
|
||||
Vite のプロキシは転送のみを行い、契約を変換しません。画面全体を実サービスにつなぐ前に、次の差を解消してください。
|
||||
|
||||
- ログイン:フロントエンドは `name` を送り `token` を読みます。Gin は `username` を受け取り `accessToken` を返します。
|
||||
- ユーザー:フロントエンドは `/api/user/profile`、Gin は `/api/user/info` を使います。
|
||||
- 商品:フロントエンドは `/api/products`、`/api/products/:id` と多言語 `name`、`priceCents` を使います。Gin は `/api/product/list`、`/api/product/detail?id=…` と `title`、`price` を使います。
|
||||
- フロントエンドに Project CRUD 契約はありますが、現在の Gin Router に対応ルートはありません。
|
||||
|
||||
## 追加機能の連携範囲
|
||||
|
||||
お気に入りの GET/POST パスは Gin に一致しますが、Gin 発行の JWT と公開商品の ID が必要です。Mock のトークンは実サービスで使えません。提案 API は公開 JSON で、ログインと切り離して確認できます。通信層が応答形式に対応していても、セッション全体の連携確認にはなりません。
|
||||
|
||||
## 確認方法
|
||||
|
||||
まず以下の API を確認し、その後にブラウザをつなぎます。`BUSINESS_USER_JWT` は実際の業務ログイン応答から取得し、アカウントはサービス側の開発設定を使ってください。古い文書の認証情報を前提にしません。Mock E2E は実 DB・サービス間連携の検証を代替しません。
|
||||
|
||||
```bash
|
||||
curl -s 'http://127.0.0.1:8001/api/ai/suggestions?locale=ja-JP'
|
||||
curl -s 'http://127.0.0.1:8002/api/product/favorite?id=1' \
|
||||
-H "Authorization: Bearer $BUSINESS_USER_JWT"
|
||||
```
|
||||
|
||||
[API](./request.md) · [AI Chat](./ai-chat.md) · [Commerce](./commerce.md)
|
||||
|
||||
@ -6,5 +6,22 @@
|
||||
|
||||
契約は OpenAPI から生成し、金額は整数の最小通貨単位で保存します。商品名、特徴、説明は `zh-CN`、`en-US`、`ja-JP` が必須です。画像 URL は同一 Origin または HTTPS だけを許可します。
|
||||
|
||||
`pnpm dev` は同じ契約の Mock、`pnpm dev:integration` は Gin/PostgreSQL を使います。Remote State は TanStack Query が管理し、Pinia には保存しません。
|
||||
`pnpm dev` は Mock、`pnpm dev:integration` は Gin/FastAPI のプロキシを設定します。実サービスを使う前に、以下の契約の差を確認してください。Remote State は TanStack Query が管理し、Pinia には保存しません。
|
||||
|
||||
## お気に入り操作とセッションの分離
|
||||
|
||||
`FavoriteButton` に数値の `productId` と現在の `session` トークンを渡します。未ログイン時はログインリンクを表示し、非公開の状態を取得しません。ログイン後は保存済みの状態を読み込んでから操作を有効にします。取得失敗時は再試行でき、保存失敗時は最後に確認した状態を保ってエラーを表示します。取得・保存中の二重送信を防ぎます。
|
||||
|
||||
状態は TanStack Query が管理します。キーはコントロールのインスタンス、セッションの世代、商品 ID から構成し、トークンを含めません。更新時に元のキーを保持するため、古い応答が別のアカウントや商品の状態を上書きしません。再マウントやセッション変更で再取得します。サーバーに状態の反転を依頼せず、明示的な真偽値を送ります。
|
||||
|
||||
```text
|
||||
GET /api/product/favorite?id=1
|
||||
POST /api/product/favorite
|
||||
{ "productId": 1, "favorite": true }
|
||||
```
|
||||
|
||||
`src/components/shop/FavoriteButton.vue` → `src/api/modules/favorites.ts` → `apiClient`.
|
||||
|
||||
応答の包装への対応は、パスや商品フィールドの変換を意味しません。単体アプリの商品 API は `/api/products` と多言語 `name`/`priceCents`、現在の Gin は `/api/product/list` と `title`/`price` です。ログインにも `name`/`token` と `username`/`accessToken` の差があります。全面的な連携を確認する前に契約を照合するか、明示的なドメインアダプターを追加してください。新しいお気に入りパスは Gin に一致しますが、認証には互換性のある発行済み JWT が必要です。
|
||||
|
||||
[API](./request.md) · [テスト](./testing.md)
|
||||
|
||||
@ -13,3 +13,12 @@ pnpm typecheck
|
||||
|
||||
`openapi/schema.yaml` と生成済み `src/types/api/generated.d.ts` を同時に Commit します。
|
||||
|
||||
## REST 契約とキャンセル
|
||||
|
||||
単体アプリの通信層は、実サービスの `code: 0`/`message` と旧 Mock の 2xx 業務コード/`msg` に対応します。いずれも `data` を返し、失敗は `ApiError` です。HTTP 2xx だけで業務の成功を判定しません。
|
||||
|
||||
以下の関数は包装を外したデータを返し、失敗は `ApiError` として通知します。取得には Query の `AbortSignal` を渡します。更新には起動時に設定した認証クライアントを使い、呼び出し側から所有者 ID を送信しません。
|
||||
|
||||
単体アプリでは `VITE_AI_API_BASE_URL`(既定 `/api/ai`)で提案を取得し、開発プロキシを `VITE_AI_API_TARGET` で指定します。通常の業務通信は Gin に送ります。JSON は `src/api/modules/ai.ts`、ストリーミングはプロバイダーと composable が担当します。
|
||||
|
||||
応答の包装への対応は、パスや商品フィールドの変換を意味しません。単体アプリの商品 API は `/api/products` と多言語 `name`/`priceCents`、現在の Gin は `/api/product/list` と `title`/`price` です。ログインにも `name`/`token` と `username`/`accessToken` の差があります。全面的な連携を確認する前に契約を照合するか、明示的なドメインアダプターを追加してください。新しいお気に入りパスは Gin に一致しますが、認証には互換性のある発行済み JWT が必要です。
|
||||
|
||||
@ -13,3 +13,16 @@ pnpm check
|
||||
|
||||
実バックエンド変更時は Compose と Smoke Script、Gin の `go test ./...`、FastAPI の Ruff/mypy/pytest も実行します。
|
||||
|
||||
## 追加機能の回帰テスト
|
||||
|
||||
API テストでは ID、本文、キャンセル、言語変換、AI の base URL とエラー伝播を確認します。コンポーネントテストでは未ログイン、保存・解除、取得の再試行、保存失敗、アカウント変更後の古い応答を検証します。ストリーミング composable は停止・キャンセル・並行した処理を検証し、リモート提案とローカルへの切り替えはブラウザで確認します。QueryClient はテストごとに作成・破棄します。
|
||||
|
||||
```bash
|
||||
pnpm test tests/api/features.test.ts tests/api/client.test.ts tests/components/FavoriteButton.test.ts
|
||||
pnpm test:coverage
|
||||
pnpm test:e2e
|
||||
```
|
||||
|
||||
Playwright は再読み込み後のお気に入り、解除、リモート提案、通信失敗時のローカル提案を確認します。ストリーミングテストは固定の質問を入力し、提案の文言に依存させません。これらは開発用 Mock の検証であり、PostgreSQL/Redis の統合テストには別の環境設定が必要です。
|
||||
|
||||
以下のアプリ用テストはアプリ側の作業ディレクトリで実行してください。この `docs` ブランチでは `pnpm build` で VitePress を検証します。現在の実行結果を確認してください。
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user