Files
mnote/wolai-frontend/src/lib/documents/tree-command-client.ts
T

109 lines
2.9 KiB
TypeScript
Raw Normal View History

"use client";
type DocumentCommandMeta = {
requestId?: string;
traceId?: string;
commandId?: string;
commandName?: string;
};
type DocumentCommandErrorPayload = {
error?: string;
};
export type DocumentCreateCommandResult = {
id: string;
title?: string | null;
parent_id?: string | null;
sort_order?: number | null;
workspace_id?: string;
access_scope?: "private" | "shared" | "public";
is_template?: boolean;
created_at?: string | null;
updated_at?: string | null;
meta?: DocumentCommandMeta;
};
export type DocumentCreateChildCommandResult = {
pageId: string;
title?: string | null;
meta?: DocumentCommandMeta;
};
type RenameDocumentInput = {
documentId: string;
workspaceId?: string | null;
title: string;
};
type MoveDocumentInput = {
documentId: string;
parentId?: string | null;
position: number;
workspaceId?: string | null;
};
type CreateChildDocumentInput = {
parentId: string | null;
title: string;
blocks: unknown[];
};
async function postDocumentCommand<TResult>(path: string, payload: unknown, fallbackMessage: string): Promise<TResult> {
const response = await fetch(path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
const body = (await response.json().catch(() => null)) as TResult | DocumentCommandErrorPayload | null;
if (!response.ok) {
const message =
body && typeof body === "object" && "error" in body && typeof body.error === "string"
? body.error
: fallbackMessage;
throw new Error(message);
}
return body as TResult;
}
export async function createDocumentCommand(parentId: string | null): Promise<DocumentCreateCommandResult> {
return postDocumentCommand<DocumentCreateCommandResult>("/api/documents/create", { parentId }, "新建页面失败,请稍后再试");
}
export async function createChildDocumentCommand(
input: CreateChildDocumentInput,
): Promise<DocumentCreateChildCommandResult> {
return postDocumentCommand<DocumentCreateChildCommandResult>(
"/api/documents/create-child",
input,
"创建子页面失败,请稍后再试",
);
}
export async function renameDocumentCommand(input: RenameDocumentInput): Promise<{ ok: true; meta?: DocumentCommandMeta }> {
return postDocumentCommand<{ ok: true; meta?: DocumentCommandMeta }>(
"/api/documents/title",
{
documentId: input.documentId,
workspaceId: input.workspaceId ?? null,
title: input.title,
},
"重命名失败,请稍后再试",
);
}
export async function moveDocumentCommand(input: MoveDocumentInput): Promise<{ ok: true; meta?: DocumentCommandMeta }> {
return postDocumentCommand<{ ok: true; meta?: DocumentCommandMeta }>(
"/api/documents/move",
{
documentId: input.documentId,
parentId: input.parentId ?? null,
position: input.position,
workspaceId: input.workspaceId ?? null,
},
"移动失败,请稍后再试",
);
}