feat: 创建类型化 API 客户端
This commit is contained in:
1 parent
02554ed86c
commit
b9939fe173
6 files changed
+174
-3
No files matched your search
+3
-3
@@ -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. 接入小程序品牌展示、服务列表和下单流程。
|
||||
|
||||
## 未决问题
|
||||
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -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": {
|
||||
|
||||
@@ -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<string, unknown>;
|
||||
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<unknown> }
|
||||
export type FetchLike = (input: string, init?: { method?: string; headers?: Record<string, string>; body?: string }) => Promise<FetchResponse>;
|
||||
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<BrandProfile> { return this.request("/public/brand"); }
|
||||
listServices(): Promise<PublicService[]> { return this.request("/public/services"); }
|
||||
createCustomerSession(code: string): Promise<{ token: string }> {
|
||||
return this.request("/customer/session/wechat", { method: "POST", body: { code } });
|
||||
}
|
||||
listCustomerBookings(): Promise<Booking[]> { return this.request("/customer/bookings"); }
|
||||
createCustomerBooking(input: CreateBookingInput): Promise<BookingSummary> {
|
||||
return this.request("/customer/bookings", { method: "POST", body: input });
|
||||
}
|
||||
cancelCustomerBooking(id: string): Promise<Booking> {
|
||||
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<AdminBooking[]> {
|
||||
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<AdminBooking> { 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<Booking> {
|
||||
return this.request(`/admin/bookings/${encodeURIComponent(id)}/status`, { method: "POST", body: { status, ...(adminNote === undefined ? {} : { adminNote }) } });
|
||||
}
|
||||
markAdminBookingRead(id: string): Promise<Booking> {
|
||||
return this.request(`/admin/bookings/${encodeURIComponent(id)}/read`, { method: "POST" });
|
||||
}
|
||||
listAdminTags(): Promise<BookingTag[]> { return this.request("/admin/bookings/tags"); }
|
||||
createAdminTag(name: string): Promise<BookingTag> {
|
||||
return this.request("/admin/bookings/tags", { method: "POST", body: { name } });
|
||||
}
|
||||
private async request<T>(path: string, options: { method?: string; body?: unknown } = {}): Promise<T> {
|
||||
const headers: Record<string, string> = { 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";
|
||||
@@ -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<string, string>; 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;
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": { "noEmit": true, "rootDir": ".." },
|
||||
"include": ["./**/*.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user