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";
|
||||
Reference in new issue
Block a user