47 lines
1.2 KiB
TypeScript
47 lines
1.2 KiB
TypeScript
import {
|
|
conversationSchema,
|
|
conversationSummarySchema,
|
|
type ConversationResponse,
|
|
type ConversationSummaryResponse,
|
|
} from "@great-agent/web-contracts";
|
|
|
|
export async function listConversations(): Promise<
|
|
ConversationSummaryResponse[]
|
|
> {
|
|
return conversationSummarySchema
|
|
.array()
|
|
.parse(await request("/api/conversations"));
|
|
}
|
|
|
|
export async function getConversation(
|
|
id: string,
|
|
): Promise<ConversationResponse> {
|
|
return conversationSchema.parse(
|
|
await request(`/api/conversations/${encodeURIComponent(id)}`),
|
|
);
|
|
}
|
|
|
|
async function request(path: string, init?: RequestInit): Promise<unknown> {
|
|
const response = await fetch(path, {
|
|
...init,
|
|
headers: { "content-type": "application/json", ...init?.headers },
|
|
});
|
|
const value = await response.json();
|
|
if (!response.ok) throw new Error(readErrorMessage(value));
|
|
return value;
|
|
}
|
|
|
|
function readErrorMessage(value: unknown): string {
|
|
if (typeof value === "object" && value && "error" in value) {
|
|
const error = value.error;
|
|
if (
|
|
typeof error === "object" &&
|
|
error &&
|
|
"message" in error &&
|
|
typeof error.message === "string"
|
|
)
|
|
return error.message;
|
|
}
|
|
return "请求失败,请稍后重试";
|
|
}
|