api.ts 11.6 KB
import type {
  ChunkRecord, ConfigResponse, DataSource, DocumentItem, DuplicatePair, EdgeDetail,
  GraphPayload, GraphStats, InfoResponse, JobItem, NodeDetail, OntologyResponse,
  QueryBrief, SmInstruction, SmMetric, SmMetricIssue, SmModel, SmRelation,
  SqlIssue, SqlPair, SqlRelationRec, SqlRunBrief,
} from "./types";

export class ApiError extends Error {
  constructor(message: string, readonly status: number, readonly kind?: string) {
    super(message);
  }
}

async function req<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(path, init);
  if (!res.ok) {
    let detail = `HTTP ${res.status}`;
    let kind: string | undefined;
    try {
      const body = await res.json();
      detail = body.detail ?? detail;
      kind = body.kind;
    } catch {
      /* 非 JSON 错误体,保留状态码文案 */
    }
    throw new ApiError(detail, res.status, kind);
  }
  if (res.status === 204) return undefined as T;
  const ct = res.headers.get("content-type") ?? "";
  return (ct.includes("json") ? res.json() : res.text()) as Promise<T>;
}

const json = (body: unknown): RequestInit => ({
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(body),
});

const put = (body: unknown): RequestInit => ({ ...json(body), method: "PUT" });

export const api = {
  info: () => req<InfoResponse>("/api/info"),
  overview: () => req<{
    info: InfoResponse; documents: DocumentItem[]; jobs: JobItem[];
    queries: QueryBrief[]; communities: { id: number; title: string; size: number; summary: string }[];
  }>("/api/overview"),

  // 文档
  documents: () => req<DocumentItem[]>("/api/documents"),
  document: (id: number) => req<DocumentItem>(`/api/documents/${id}`),
  upload: (file: File, onProgress?: (pct: number) => void) =>
    new Promise<DocumentItem>((resolve, reject) => {
      const fd = new FormData();
      fd.append("file", file);
      const xhr = new XMLHttpRequest();
      xhr.open("POST", "/api/documents");
      xhr.upload.onprogress = (e) => {
        if (e.lengthComputable) onProgress?.(Math.round((e.loaded / e.total) * 100));
      };
      xhr.onload = () => {
        let body: any = {};
        try { body = JSON.parse(xhr.responseText); } catch { /* ignore */ }
        if (xhr.status >= 200 && xhr.status < 300) resolve(body);
        else reject(new ApiError(body.detail ?? `HTTP ${xhr.status}`, xhr.status, body.kind));
      };
      xhr.onerror = () => reject(new ApiError("网络错误,上传失败", 0));
      xhr.send(fd);
    }),
  startExtract: (id: number) =>
    req<{ job_id: number; already_running: boolean; queue_depth?: number }>(
      `/api/documents/${id}/extract`, { method: "POST" }),
  deleteDocument: (id: number) =>
    req<{ ok: boolean; removed_entities: number; removed_relations: number; removed_chunks: number }>(
      `/api/documents/${id}`, { method: "DELETE" }),
  documentChunks: (id: number, preview = false) =>
    req<{ preview: boolean; encoding?: string; warnings?: string[]; chunks: ChunkRecord[] }>(
      `/api/documents/${id}/chunks?preview=${preview}`),
  documentEntities: (id: number) =>
    req<{ total: number; items: { id: string; label: string; type: string; degree: number; description: string }[] }>(
      `/api/documents/${id}/entities`),

  // 任务
  jobs: (limit = 20) => req<JobItem[]>(`/api/jobs?limit=${limit}`),
  job: (id: number) => req<JobItem>(`/api/jobs/${id}`),

  // 图谱
  graph: (p: {
    type?: string; relation?: string; keyword?: string;
    docId?: number | null; minDegree?: number; limit?: number;
  }) => {
    const q = new URLSearchParams();
    if (p.type) q.set("type", p.type);
    if (p.relation) q.set("relation", p.relation);
    if (p.keyword) q.set("keyword", p.keyword);
    if (p.docId != null) q.set("doc_id", String(p.docId));
    if (p.minDegree) q.set("min_degree", String(p.minDegree));
    q.set("limit", String(p.limit ?? 500));
    return req<GraphPayload>(`/api/graph?${q}`);
  },
  ego: (node: string, hops = 1, limit = 300) =>
    req<GraphPayload>(`/api/graph/ego?node=${encodeURIComponent(node)}&hops=${hops}&limit=${limit}`),
  graphStats: () => req<GraphStats>("/api/graph/stats"),
  searchNodes: (q: string, limit = 10) =>
    req<{ id: string; label: string; type: string; degree: number; description: string; match: string }[]>(
      `/api/graph/search?q=${encodeURIComponent(q)}&limit=${limit}`),
  node: (id: string) => req<NodeDetail>(`/api/node?id=${encodeURIComponent(id)}`),
  updateNode: (body: { id: string; type?: string; description?: string; verified?: boolean }) =>
    req<{ ok: boolean; node: NodeDetail }>("/api/node", put(body)),
  edge: (source: string, target: string, relation: string) =>
    req<EdgeDetail>(`/api/edge?source=${encodeURIComponent(source)}&target=${
      encodeURIComponent(target)}&relation=${encodeURIComponent(relation)}`),
  updateEdge: (body: { source: string; target: string; relation: string; description?: string; verified?: boolean }) =>
    req<{ ok: boolean }>("/api/edge", put(body)),
  duplicates: (limit = 200) => req<DuplicatePair[]>(`/api/graph/duplicates?limit=${limit}`),
  mergeNodes: (keep: string, drop: string[]) =>
    req<{ ok: boolean; merged: string[] }>("/api/graph/merge", json({ keep, drop })),
  deleteNodes: (ids: string[]) =>
    req<{ ok: boolean; removed: number }>("/api/graph/nodes/delete", json({ ids })),
  clearGraph: () => req<{ ok: boolean }>("/api/graph/clear", { method: "POST" }),
  exportUrl: (format: "json" | "graphml") => `/api/graph/export?format=${format}`,

  // 检索
  queries: (limit = 20) => req<QueryBrief[]>(`/api/queries?limit=${limit}`),
  queryDetail: (id: number) => req<any>(`/api/queries/${id}`),
  chunk: (id: string) => req<ChunkRecord>(`/api/chunk?id=${encodeURIComponent(id)}`),

  // 设置
  config: () => req<ConfigResponse>("/api/config"),
  saveConfig: (items: Record<string, string>) =>
    req<{ ok: boolean; saved: string[] }>("/api/config", put({ items })),
  ontology: () => req<OntologyResponse>("/api/ontology"),
  saveOntology: (entity_types: string[], relation_types: string[]) =>
    req<{ ok: boolean }>("/api/ontology", put({ entity_types, relation_types })),
  clearCache: () => req<{ ok: boolean }>("/api/cache/clear", { method: "POST" }),

  // 数据问答
  sqlMeta: () => req<{ supported_types: string[]; crypto_ready: boolean; row_limit: number; timeout_ms: number }>(
    "/api/sql/meta"),

  datasources: () => req<DataSource[]>("/api/sql/datasources"),
  createDatasource: (body: Record<string, unknown>) => req<DataSource>("/api/sql/datasources", json(body)),
  updateDatasource: (id: number, body: Record<string, unknown>) =>
    req<DataSource>(`/api/sql/datasources/${id}`, put(body)),
  deleteDatasource: (id: number) =>
    req<{ ok: boolean }>(`/api/sql/datasources/${id}`, { method: "DELETE" }),
  testDatasource: (id: number) =>
    req<{ version: string; database: string; table_count: number; account_writable: boolean | null; warning?: string }>(
      `/api/sql/datasources/${id}/test`, { method: "POST" }),
  introspect: (id: number, resample = false) =>
    req<{ job_id: number; queued: boolean; queue_depth: number }>(
      `/api/sql/datasources/${id}/introspect?resample=${resample}`, { method: "POST" }),

  sqlModels: (dsId: number, enabledOnly = false) =>
    req<SmModel[]>(`/api/sql/datasources/${dsId}/models?enabled_only=${enabledOnly}`),
  updateSqlModel: (id: number, body: Record<string, unknown>) =>
    req<{ ok: boolean }>(`/api/sql/models/${id}`, put(body)),
  updateSqlColumn: (id: number, body: Record<string, unknown>) =>
    req<{ ok: boolean }>(`/api/sql/columns/${id}`, put(body)),
  enableSqlModels: (dsId: number, ids: number[], enabled: boolean) =>
    req<{ ok: boolean; changed: number }>(
      `/api/sql/datasources/${dsId}/models/enable`, json({ ids, enabled })),

  sqlRelations: (dsId: number) => req<SmRelation[]>(`/api/sql/datasources/${dsId}/relations`),
  upsertSqlRelation: (dsId: number, body: Record<string, unknown>) =>
    req<{ ok: boolean; id: number }>(`/api/sql/datasources/${dsId}/relations`, json(body)),
  deleteSqlRelation: (id: number) =>
    req<{ ok: boolean }>(`/api/sql/relations/${id}`, { method: "DELETE" }),
  mdlUrl: (dsId: number) => `/api/sql/datasources/${dsId}/mdl`,

  describeSchema: (dsId: number, body: { overwrite?: boolean; model_ids?: number[] } = {}) =>
    req<{ job_id: number; queued: boolean; queue_depth: number }>(
      `/api/sql/datasources/${dsId}/describe`, json({ overwrite: false, model_ids: [], ...body })),
  recommendRelations: (dsId: number) =>
    req<SqlRelationRec[]>(`/api/sql/datasources/${dsId}/relations/recommend`),

  sqlMetrics: (dsId: number) => req<SmMetric[]>(`/api/sql/datasources/${dsId}/metrics`),
  metricIssues: (dsId: number) => req<SmMetricIssue[]>(`/api/sql/datasources/${dsId}/metrics/issues`),

  /** 给还没分类的指标与规则补一个分类。只填空,不覆盖人工改过的 */
  categorize: (dsId: number) =>
    req<{ ok: boolean; metrics: number; instructions: number }>(
      `/api/sql/datasources/${dsId}/categorize`, { method: "POST" }),
  upsertMetric: (dsId: number, body: Record<string, unknown>) =>
    req<{ ok: boolean; id: number }>(`/api/sql/datasources/${dsId}/metrics`, json(body)),
  deleteMetric: (id: number) => req<{ ok: boolean }>(`/api/sql/metrics/${id}`, { method: "DELETE" }),

  sqlInstructions: (dsId = 0) => req<SmInstruction[]>(`/api/sql/instructions?ds_id=${dsId}`),
  upsertInstruction: (body: Record<string, unknown>) =>
    req<{ ok: boolean; id: number }>("/api/sql/instructions", json(body)),
  deleteInstruction: (id: number) =>
    req<{ ok: boolean }>(`/api/sql/instructions/${id}`, { method: "DELETE" }),

  validateSql: (body: { ds_id: number; sql: string }) =>
    req<{ ok: boolean; sql: string; limited: boolean; tables: string[]; issues: SqlIssue[] }>(
      "/api/sql/validate", json(body)),
  runSql: (body: { ds_id: number; sql: string; question?: string; thread_id?: string; origin_sql?: string }) =>
    req<{
      ok: boolean; run_id: number; pair_id: number; columns: string[]; rows: unknown[][];
      row_count: number; duration_ms: number; truncated: boolean; sql: string;
      limited: boolean; issues: SqlIssue[];
    }>("/api/sql/run", json(body)),

  /** 按需解释一条 SQL。默认折叠着,展开了才值得花一轮大模型往返 */
  explainSql: (body: { ds_id: number; question: string; sql: string }) =>
    req<{ ok: boolean; text: string }>("/api/sql/explain", json(body)),

  /** 手改 SQL 重跑之后补一份结论。/run 不经管线,自然也不会自带结论 */
  summarize: (body: {
    ds_id: number; question: string; columns: string[]; rows: unknown[][]; row_count: number;
  }) => req<{ ok: boolean; text: string }>("/api/sql/summarize", json(body)),

  sqlRuns: (dsId?: number, limit = 30) =>
    req<SqlRunBrief[]>(`/api/sql/runs?limit=${limit}${dsId ? `&ds_id=${dsId}` : ""}`),
  rateSqlRun: (id: number, rating: number) =>
    req<{ ok: boolean }>(`/api/sql/runs/${id}/rate?rating=${rating}`, { method: "POST" }),

  sqlPairs: (p: { dsId?: number; status?: string; keyword?: string; limit?: number } = {}) => {
    const q = new URLSearchParams();
    if (p.dsId) q.set("ds_id", String(p.dsId));
    if (p.status) q.set("status", p.status);
    if (p.keyword) q.set("keyword", p.keyword);
    q.set("limit", String(p.limit ?? 100));
    return req<SqlPair[]>(`/api/sql/pairs?${q}`);
  },
  createSqlPair: (body: Record<string, unknown>) => req<{ ok: boolean; id: number }>("/api/sql/pairs", json(body)),
  updateSqlPair: (id: number, body: Record<string, unknown>) => req<SqlPair>(`/api/sql/pairs/${id}`, put(body)),
  adoptSqlPair: (id: number) => req<SqlPair>(`/api/sql/pairs/${id}/adopt`, { method: "POST" }),
  deleteSqlPair: (id: number) => req<{ ok: boolean }>(`/api/sql/pairs/${id}`, { method: "DELETE" }),
};