diff --git a/PROJECT_STATUS.md b/PROJECT_STATUS.md index a8832b3..cd7d682 100644 --- a/PROJECT_STATUS.md +++ b/PROJECT_STATUS.md @@ -35,6 +35,7 @@ - API 已通过真实 HTTP 验证:健康检查、公开品牌/服务读取和管理员登录。 - HTTP 集成测试:公开接口、管理员登录、错误密码、管理员权限边界、客户会话、预约 DTO 校验、创建/取消和状态流转,共 8 项通过。 - OpenAPI 3.1 契约:`docs/openapi.yaml`,覆盖当前公开、客户和管理员接口。 +- 类型化 `@personal-brand/api-client`:支持公开内容、客户预约、管理员订单和统一错误处理,并有 2 项客户端测试。 - 已执行多轮 Codex 代码审查并修复关键认证和权限问题。 ## 最近提交 @@ -52,9 +53,8 @@ b89853b fix: harden api authentication and validation ## 下一步优先级 -1. 创建类型化 `api-client`,固定前后端接口边界。 -2. 接入管理后台订单处理页面。 -3. 接入小程序品牌展示、服务列表和下单流程。 +1. 接入管理后台订单处理页面。 +2. 接入小程序品牌展示、服务列表和下单流程。 ## 未决问题 diff --git a/eslint.config.mjs b/eslint.config.mjs index cda607e..ff99adf 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -36,4 +36,12 @@ export default tseslint.config( "@typescript-eslint/require-await": "off", }, }, + { + files: ["packages/api-client/test/**/*.ts"], + rules: { + "@typescript-eslint/no-unsafe-call": "off", + "@typescript-eslint/no-unsafe-member-access": "off", + "@typescript-eslint/require-await": "off", + }, + }, ); diff --git a/package.json b/package.json index 246285c..9ad8411 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "check": "pnpm format:check && pnpm lint && pnpm typecheck", "db:migrate": "pnpm --filter @personal-brand/api db:migrate", "db:seed": "pnpm --filter @personal-brand/api db:seed", + "test:api-client": "pnpm --filter @personal-brand/api exec tsx --test ../../packages/api-client/test/**/*.test.ts", "clean": "turbo run clean && rimraf node_modules .turbo" }, "devDependencies": { diff --git a/packages/api-client/src/index.ts b/packages/api-client/src/index.ts index f2a76a6..4523cb6 100644 --- a/packages/api-client/src/index.ts +++ b/packages/api-client/src/index.ts @@ -1 +1,117 @@ +import type { + BookingRequestType, + BookingStatus, + ContactPreference, + FulfillmentType, + PublicService, +} from "@personal-brand/types"; + +export interface BrandProfile { + id: string; + name: string; + tagline: string | null; + description: string | null; + avatarUrl: string | null; + coverUrl: string | null; + hours: string | null; + address: string | null; + deliveryNote: string | null; +} + +export interface BookingItemInput { serviceId: string; quantity: number } +export interface CreateBookingInput { + requestType: BookingRequestType; + customerName: string; + phone?: string; + wechatId?: string; + contactPreference: ContactPreference; + fulfillmentType?: FulfillmentType; + serviceId?: string; + requestedDate?: string; + requestedTime?: string; + deliveryAddress?: string; + note?: string; + extraData?: Record; + items: BookingItemInput[]; +} +export interface BookingSummary { bookingNo: string; status: BookingStatus; estimatedAmount: number | null; createdAt: string } +export interface Booking extends BookingSummary { id: string; customerName: string; adminNote?: string | null } +export interface BookingTag { id: string; name: string; isPreset: boolean; isEnabled: boolean } +export interface AdminBooking extends Booking { tags?: Array<{ tag: BookingTag }> } +export interface ApiErrorBody { data: null; error: { code: string; message: string }; requestId: string | null } + +export class ApiClientError extends Error { + constructor(readonly status: number, readonly body: ApiErrorBody) { + super(body.error.message); + this.name = "ApiClientError"; + } + get code(): string { return this.body.error.code; } + get requestId(): string | null { return this.body.requestId; } +} + +export interface FetchResponse { readonly status: number; readonly ok: boolean; json(): Promise } +export type FetchLike = (input: string, init?: { method?: string; headers?: Record; body?: string }) => Promise; +export interface ApiClientOptions { baseUrl: string; fetcher: FetchLike; token?: string } + +export class ApiClient { + private readonly baseUrl: string; + private readonly fetcher: FetchLike; + private token: string | undefined; + + constructor(options: ApiClientOptions) { + this.baseUrl = options.baseUrl.replace(/\/$/, ""); + this.fetcher = options.fetcher; + this.token = options.token; + } + setToken(token: string | undefined): void { this.token = token; } + getBrand(): Promise { return this.request("/public/brand"); } + listServices(): Promise { return this.request("/public/services"); } + createCustomerSession(code: string): Promise<{ token: string }> { + return this.request("/customer/session/wechat", { method: "POST", body: { code } }); + } + listCustomerBookings(): Promise { return this.request("/customer/bookings"); } + createCustomerBooking(input: CreateBookingInput): Promise { + return this.request("/customer/bookings", { method: "POST", body: input }); + } + cancelCustomerBooking(id: string): Promise { + return this.request(`/customer/bookings/${encodeURIComponent(id)}/cancel`, { method: "POST" }); + } + loginAdmin(username: string, password: string): Promise<{ token: string; displayName: string }> { + return this.request("/admin/session/login", { method: "POST", body: { username, password } }); + } + listAdminBookings(filters: { status?: BookingStatus; unreadOnly?: boolean; tagId?: string } = {}): Promise { + const params: string[] = []; + if (filters.status) params.push(`status=${encodeURIComponent(filters.status)}`); + if (filters.unreadOnly !== undefined) params.push(`unreadOnly=${filters.unreadOnly}`); + if (filters.tagId) params.push(`tagId=${encodeURIComponent(filters.tagId)}`); + const query = params.join("&"); + return this.request(`/admin/bookings${query ? `?${query}` : ""}`); + } + getAdminBooking(id: string): Promise { return this.request(`/admin/bookings/${encodeURIComponent(id)}`); } + getAdminUnreadCount(): Promise<{ count: number }> { return this.request("/admin/bookings/unread-count"); } + updateAdminBookingStatus(id: string, status: BookingStatus, adminNote?: string): Promise { + return this.request(`/admin/bookings/${encodeURIComponent(id)}/status`, { method: "POST", body: { status, ...(adminNote === undefined ? {} : { adminNote }) } }); + } + markAdminBookingRead(id: string): Promise { + return this.request(`/admin/bookings/${encodeURIComponent(id)}/read`, { method: "POST" }); + } + listAdminTags(): Promise { return this.request("/admin/bookings/tags"); } + createAdminTag(name: string): Promise { + return this.request("/admin/bookings/tags", { method: "POST", body: { name } }); + } + private async request(path: string, options: { method?: string; body?: unknown } = {}): Promise { + const headers: Record = { accept: "application/json" }; + if (options.body !== undefined) headers["content-type"] = "application/json"; + if (this.token) headers.authorization = `Bearer ${this.token}`; + const response = await this.fetcher(`${this.baseUrl}${path}`, { + method: options.method ?? "GET", + headers, + ...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }), + }); + const body = await response.json(); + if (!response.ok) throw new ApiClientError(response.status, body as ApiErrorBody); + return body as T; + } +} + export const apiClientName = "personal-brand-api-client"; diff --git a/packages/api-client/test/client.test.ts b/packages/api-client/test/client.test.ts new file mode 100644 index 0000000..092129e --- /dev/null +++ b/packages/api-client/test/client.test.ts @@ -0,0 +1,41 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { ApiClient, ApiClientError, type FetchResponse } from "../src/index.js"; + +function response(body: unknown, status = 200): FetchResponse { + return { status, ok: status >= 200 && status < 300, json: async () => body }; +} + +test("客户端发送认证头、查询参数和 JSON 请求体", async () => { + const calls: Array<{ url: string; init?: { headers?: Record; body?: string } }> = []; + const client = new ApiClient({ + baseUrl: "http://api.test/", + token: "token-1", + fetcher: async (url, init) => { + calls.push({ url, init }); + return response({ count: 2 }); + }, + }); + await client.listAdminBookings({ status: "received", unreadOnly: true, tagId: "tag/1" }); + await client.createAdminTag("重点"); + assert.equal(calls[0]?.url, "http://api.test/admin/bookings?status=received&unreadOnly=true&tagId=tag%2F1"); + assert.equal(calls[0]?.init?.headers?.authorization, "Bearer token-1"); + assert.equal(calls[1]?.init?.body, JSON.stringify({ name: "重点" })); +}); + +test("客户端将统一错误响应转换为 ApiClientError", async () => { + const client = new ApiClient({ + baseUrl: "http://api.test", + fetcher: async () => response({ data: null, error: { code: "HTTP_401", message: "无权限" }, requestId: "req-1" }, 401), + }); + await assert.rejects( + () => client.getAdminUnreadCount(), + (error: unknown) => { + assert.ok(error instanceof ApiClientError); + assert.equal(error.status, 401); + assert.equal(error.code, "HTTP_401"); + assert.equal(error.requestId, "req-1"); + return true; + }, + ); +}); diff --git a/packages/api-client/test/tsconfig.json b/packages/api-client/test/tsconfig.json new file mode 100644 index 0000000..f06adb3 --- /dev/null +++ b/packages/api-client/test/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { "noEmit": true, "rootDir": ".." }, + "include": ["./**/*.ts"] +}