feat: 创建类型化 API 客户端
This commit is contained in:
1 parent
02554ed86c
commit
b9939fe173
6 files changed
+174
-3
No files matched your search
@@ -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