feat(docs): 新增合思开放平台官方接口文档检索独立业务域与 CLI 客户端
- 新增 `src/domains/docs/` 领域(api.ts, tools.ts, types.ts, README.docs.md, docs.test.ts) - 实现从线上 `docs.ekuaibao.com/search-index.json` 实时拉取最新规范与端点提取能力 - 集成多级缓存(L1 内存 + L2 SQLite)与 `specs/docs-catalog.json` 静态预编译保底,支持零网络离线毫秒级检索 - 提供 270+ 个 OpenAPI HTTP 接口端点、参数表格、CURL 示范与成功响应示例的高精度解析与结构化输出 - 注册 `hose-use docs` CLI 命令(search, show, categories, sync)及 `doc`, `api-doc` 别名 - 严格遵循 AGENTS.md 架构分层约束,全量 1144+ 自动化单测与 tsc 类型检查 100% 通过
This commit is contained in:
1 parent
448dd438ff
commit
4f572ad9c1
11 files changed
+1013
-2
No files matched your search
@@ -2,7 +2,7 @@
|
||||
|
||||
本目录按业务域组织代码,每个域独立负责自己的传输层(`api.ts`)、业务编排层(`tools.ts` / `services.ts`)和模型层(`types.ts`)。
|
||||
|
||||
## 当前域(共 14 个)
|
||||
## 当前域(共 15 个)
|
||||
|
||||
| 域 | 内部形态 | 说明 | 详细文档 |
|
||||
|---|---|---|---|
|
||||
@@ -20,10 +20,11 @@
|
||||
| `message/` | `api / tools / types` | 系统通知消息分页查询与已读状态标记 | [README.message.md](./message/README.message.md) |
|
||||
| `task/` | `api / tools / types` | 待办/已办审批任务流分页查询与汇总 | [README.task.md](./task/README.task.md) |
|
||||
| `events/` | `poller / store / types` | 待办与未读消息增量事件轮询及基于 `core/db` (`observed_events`) 的去重存储 | [README.events.md](./events/README.events.md) |
|
||||
| `docs/` | `api / tools / types` | 合思开放平台官方文档中心(270+ API 端点)在线实时拉取、离线缓存与参数规格检索 | [README.docs.md](./docs/README.docs.md) |
|
||||
|
||||
## 分层与形态规则
|
||||
|
||||
1. **标准三件套形态**(`contact`, `dimension`, `feetype`, `menu`, `message`, `permission`, `role`, `store`, `task`):
|
||||
1. **标准三件套形态**(`contact`, `dimension`, `docs`, `feetype`, `menu`, `message`, `permission`, `role`, `store`, `task`):
|
||||
- `api.ts`:只负责 HTTP 请求和响应校验
|
||||
- `tools.ts`:纯函数式业务编排,供 CLI 命令(`src/cli/commands/*`)调用
|
||||
- `types.ts`:Zod schema 与类型定义
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Docs 开放平台文档域说明
|
||||
|
||||
本域提供合思/易快报开放平台官方文档中心(`docs.ekuaibao.com`)全量 API 规范、请求方法、URL 路径、参数表格、CURL 示例与响应 JSON 的结构化离线/在线检索与详情提取能力。
|
||||
|
||||
## 架构
|
||||
|
||||
- `api.ts`:传输层,负责实时拉取线上 `https://docs.ekuaibao.com/search-index.json` 并解析出包含 270+ 接口的结构化目录(DocCatalog)。
|
||||
- `tools.ts`:业务层,提供多级缓存(L1 内存 + L2 SQLite + `specs/docs-catalog.json` 静态预编译保底)、关键词评分加权检索、按 URL/Path/标题精确解析文档详情及业务模块分类汇总。
|
||||
- `types.ts`:Zod 模式与 TypeScript 类型定义(`OpenApiDocItem`, `DocCatalog`, `DocSearchQuery`, `DocSearchResult`)。
|
||||
|
||||
## 核心接口
|
||||
|
||||
- `searchDocs(query, options)`: 按关键词、分类(`category`)、HTTP 方法(`method`)与接口路径(`path`)智能打分检索
|
||||
- `getDocDetail(target, options)`: 快速按 ID、Path、URL 或中文标题检索出完整的接口定义
|
||||
- `listCategories(options)`: 汇总开放平台 26+ 个业务分类及对应的文档和端点总数
|
||||
- `syncDocsCatalog(options)`: 强制与线上文档站点执行全量同步并更新本地缓存
|
||||
@@ -0,0 +1,181 @@
|
||||
import ky from "ky";
|
||||
import { EkbApiError } from "../../core/errors.js";
|
||||
import {
|
||||
DocCatalogSchema,
|
||||
type DocCatalog,
|
||||
type OpenApiDocItem,
|
||||
} from "./types.js";
|
||||
|
||||
export const DEFAULT_DOCS_BASE_URL = "https://docs.ekuaibao.com";
|
||||
|
||||
interface RawSearchDoc {
|
||||
i: number;
|
||||
t: string;
|
||||
u: string;
|
||||
b?: string[];
|
||||
h?: string;
|
||||
p?: number;
|
||||
s?: string;
|
||||
}
|
||||
|
||||
interface RawSearchSection {
|
||||
documents?: RawSearchDoc[];
|
||||
index?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function parseRawSearchIndexToCatalog(
|
||||
rawSections: RawSearchSection[],
|
||||
baseUrl = DEFAULT_DOCS_BASE_URL
|
||||
): DocCatalog {
|
||||
const rawDocs = rawSections[0]?.documents || [];
|
||||
const rawHeadings = rawSections[1]?.documents || [];
|
||||
const rawParagraphs = rawSections[2]?.documents || [];
|
||||
|
||||
const apiDocs = rawDocs.filter((d) => d.u?.startsWith("/docs/open-api/"));
|
||||
const items: OpenApiDocItem[] = [];
|
||||
|
||||
for (const doc of apiDocs) {
|
||||
const headings = rawHeadings
|
||||
.filter((h) => h.p === doc.i)
|
||||
.map((h) => h.t)
|
||||
.filter(Boolean);
|
||||
const paragraphs = rawParagraphs.filter((p) => p.p === doc.i);
|
||||
|
||||
let method: string | undefined;
|
||||
let path: string | undefined;
|
||||
let curl: string | undefined;
|
||||
let responseSample: string | undefined;
|
||||
let parameters: string | undefined;
|
||||
const sections: Array<{ title: string; content: string }> = [];
|
||||
|
||||
for (const p of paragraphs) {
|
||||
const sectionTitle = p.s || "概述";
|
||||
const text = (p.t || "").trim();
|
||||
if (!text) continue;
|
||||
|
||||
// Extract HTTP method and path from paragraph text
|
||||
if (!method || !path) {
|
||||
const methodMatch = text.match(
|
||||
/\b(GET|POST|PUT|DELETE|PATCH)\s*(\/api\/[^\s]+)/i
|
||||
);
|
||||
if (methodMatch) {
|
||||
method = methodMatch[1].toUpperCase();
|
||||
path = methodMatch[2];
|
||||
}
|
||||
}
|
||||
|
||||
// Extract CURL
|
||||
if (
|
||||
sectionTitle === "CURL" ||
|
||||
text.startsWith("curl ") ||
|
||||
text.includes("curl --location")
|
||||
) {
|
||||
curl = text;
|
||||
// Fallback method/path extraction from curl if not found yet
|
||||
if (!method || !path) {
|
||||
const curlMatch = text.match(
|
||||
/--request\s+(GET|POST|PUT|DELETE|PATCH)\s+['"][^'"]*?(\/api\/[^?'"\s]+)/i
|
||||
);
|
||||
if (curlMatch) {
|
||||
method = curlMatch[1].toUpperCase();
|
||||
path = curlMatch[2];
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
sectionTitle === "成功响应" ||
|
||||
sectionTitle === "Response" ||
|
||||
(text.startsWith("{") && text.endsWith("}"))
|
||||
) {
|
||||
responseSample = text;
|
||||
} else if (
|
||||
sectionTitle.includes("Parameter") ||
|
||||
sectionTitle.includes("参数") ||
|
||||
sectionTitle.includes("Body")
|
||||
) {
|
||||
parameters = parameters ? `${parameters}\n${text}` : text;
|
||||
}
|
||||
|
||||
sections.push({
|
||||
title: sectionTitle,
|
||||
content: text,
|
||||
});
|
||||
}
|
||||
|
||||
const category = doc.b?.[1] || "未分类";
|
||||
const cleanUrl = doc.u || "";
|
||||
|
||||
items.push({
|
||||
id: doc.i,
|
||||
title: doc.t || "未命名文档",
|
||||
category,
|
||||
url: cleanUrl,
|
||||
permalink: `${baseUrl.replace(/\/+$/, "")}${cleanUrl}`,
|
||||
method,
|
||||
path,
|
||||
breadcrumbs: doc.b || [],
|
||||
headings,
|
||||
sections,
|
||||
parameters,
|
||||
curl,
|
||||
responseSample,
|
||||
});
|
||||
}
|
||||
|
||||
const catalog: DocCatalog = {
|
||||
version: "1.0.0",
|
||||
updatedAt: new Date().toISOString(),
|
||||
sourceUrl: `${baseUrl.replace(/\/+$/, "")}/search-index.json`,
|
||||
totalDocs: items.length,
|
||||
totalEndpoints: items.filter((i) => i.method && i.path).length,
|
||||
items,
|
||||
};
|
||||
|
||||
return DocCatalogSchema.parse(catalog);
|
||||
}
|
||||
|
||||
/**
|
||||
* 实时从线上文档站点获取最新接口定义索引
|
||||
*/
|
||||
export async function fetchLiveDocsCatalog(options?: {
|
||||
baseUrl?: string;
|
||||
timeoutMs?: number;
|
||||
}): Promise<DocCatalog> {
|
||||
const baseUrl = options?.baseUrl || DEFAULT_DOCS_BASE_URL;
|
||||
const timeoutMs = options?.timeoutMs ?? 15000;
|
||||
const targetUrl = `${baseUrl.replace(/\/+$/, "")}/search-index.json`;
|
||||
|
||||
try {
|
||||
const response = await ky.get(targetUrl, {
|
||||
timeout: timeoutMs,
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "hose-use/docs-client",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new EkbApiError(
|
||||
`获取开放平台文档索引失败: HTTP ${response.status}`,
|
||||
"DOCS_FETCH_FAILED",
|
||||
response.status
|
||||
);
|
||||
}
|
||||
|
||||
const raw = (await response.json()) as RawSearchSection[];
|
||||
if (!Array.isArray(raw) || raw.length === 0) {
|
||||
throw new EkbApiError(
|
||||
"开放平台文档索引数据异常: 返回格式不是有效的分区数组",
|
||||
"DOCS_INVALID_DATA"
|
||||
);
|
||||
}
|
||||
|
||||
return parseRawSearchIndexToCatalog(raw, baseUrl);
|
||||
} catch (error: any) {
|
||||
if (error instanceof EkbApiError) throw error;
|
||||
throw new EkbApiError(
|
||||
`请求开放平台文档站点 (${targetUrl}) 失败: ${error?.message || String(error)}`,
|
||||
"DOCS_NETWORK_ERROR",
|
||||
502
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { parseRawSearchIndexToCatalog } from "./api.js";
|
||||
import {
|
||||
getDocDetail,
|
||||
getDocsCatalog,
|
||||
listCategories,
|
||||
searchDocs,
|
||||
} from "./tools.js";
|
||||
|
||||
const mockRawSections = [
|
||||
{
|
||||
documents: [
|
||||
{
|
||||
i: 1001,
|
||||
t: "查询角色组和角色",
|
||||
u: "/docs/open-api/corporation/get-roles-group",
|
||||
b: ["Open API", "企业通讯录"],
|
||||
},
|
||||
{
|
||||
i: 1002,
|
||||
t: "下载附件",
|
||||
u: "/docs/open-api/attachment/attachment-download",
|
||||
b: ["Open API", "附件"],
|
||||
},
|
||||
{
|
||||
i: 1003,
|
||||
t: "其他非 API 页面",
|
||||
u: "/blog/archive",
|
||||
b: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
documents: [
|
||||
{
|
||||
i: 2001,
|
||||
t: "Query Parameters",
|
||||
u: "/docs/open-api/corporation/get-roles-group",
|
||||
h: "#query-parameters",
|
||||
p: 1001,
|
||||
},
|
||||
{
|
||||
i: 2002,
|
||||
t: "CURL",
|
||||
u: "/docs/open-api/corporation/get-roles-group",
|
||||
h: "#curl",
|
||||
p: 1001,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
documents: [
|
||||
{
|
||||
i: 3001,
|
||||
t: "GET /api/openapi/v1/roleDefGroups 更新日志 0.7.135 🆕 新增了本接口。",
|
||||
s: "查询角色组和角色",
|
||||
p: 1001,
|
||||
},
|
||||
{
|
||||
i: 3002,
|
||||
t: "accessToken String 认证token 必填 - 通过 获取授权 获取 accessToken",
|
||||
s: "Query Parameters",
|
||||
p: 1001,
|
||||
},
|
||||
{
|
||||
i: 3003,
|
||||
t: "curl --location --request GET 'https://app.ekuaibao.com/api/openapi/v1/roleDefGroups?accessToken=TOKEN'",
|
||||
s: "CURL",
|
||||
p: 1001,
|
||||
},
|
||||
{
|
||||
i: 3004,
|
||||
t: "POST /api/openapi/v2/attachment/downloadurls",
|
||||
s: "下载附件",
|
||||
p: 1002,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
describe("Docs Domain - 开放平台文档域", () => {
|
||||
it("parseRawSearchIndexToCatalog 正确解析原始搜索索引并提取 HTTP 属性", () => {
|
||||
const catalog = parseRawSearchIndexToCatalog(mockRawSections as any);
|
||||
expect(catalog.totalDocs).toBe(2);
|
||||
expect(catalog.totalEndpoints).toBe(2);
|
||||
|
||||
const roleGroupDoc = catalog.items.find((i) => i.id === 1001);
|
||||
expect(roleGroupDoc).toBeDefined();
|
||||
expect(roleGroupDoc?.title).toBe("查询角色组和角色");
|
||||
expect(roleGroupDoc?.category).toBe("企业通讯录");
|
||||
expect(roleGroupDoc?.method).toBe("GET");
|
||||
expect(roleGroupDoc?.path).toBe("/api/openapi/v1/roleDefGroups");
|
||||
expect(roleGroupDoc?.curl).toContain("/api/openapi/v1/roleDefGroups");
|
||||
expect(roleGroupDoc?.parameters).toContain("accessToken");
|
||||
|
||||
const attachmentDoc = catalog.items.find((i) => i.id === 1002);
|
||||
expect(attachmentDoc?.method).toBe("POST");
|
||||
expect(attachmentDoc?.path).toBe("/api/openapi/v2/attachment/downloadurls");
|
||||
});
|
||||
|
||||
it("getDocsCatalog 在测试环境中能安全加载预编译/内嵌规格", async () => {
|
||||
const catalog = await getDocsCatalog();
|
||||
expect(catalog.items.length).toBeGreaterThan(100);
|
||||
expect(catalog.totalEndpoints).toBeGreaterThan(100);
|
||||
});
|
||||
|
||||
it("searchDocs 按关键词检索接口并正确排序", async () => {
|
||||
const res = await searchDocs({ keyword: "roleDefGroups" });
|
||||
expect(res.total).toBeGreaterThanOrEqual(1);
|
||||
expect(res.items[0]?.path).toBe("/api/openapi/v1/roleDefGroups");
|
||||
expect(res.items[0]?.title).toBe("查询角色组和角色");
|
||||
});
|
||||
|
||||
it("searchDocs 支持按分类与 HTTP 方法精确过滤", async () => {
|
||||
const res = await searchDocs({
|
||||
category: "企业通讯录",
|
||||
method: "GET",
|
||||
});
|
||||
expect(res.items.length).toBeGreaterThanOrEqual(1);
|
||||
for (const item of res.items) {
|
||||
expect(item.category).toBe("企业通讯录");
|
||||
expect(item.method).toBe("GET");
|
||||
}
|
||||
});
|
||||
|
||||
it("getDocDetail 能按路径、URL、标题或 ID 精准定位文档", async () => {
|
||||
const byPath = await getDocDetail("/api/openapi/v1/roleDefGroups");
|
||||
expect(byPath).toBeDefined();
|
||||
expect(byPath?.title).toBe("查询角色组和角色");
|
||||
|
||||
const byUrl = await getDocDetail("/docs/open-api/corporation/get-roles-group");
|
||||
expect(byUrl).toBeDefined();
|
||||
expect(byUrl?.id).toBe(byPath?.id);
|
||||
|
||||
const byTitle = await getDocDetail("查询角色组和角色");
|
||||
expect(byTitle?.path).toBe("/api/openapi/v1/roleDefGroups");
|
||||
});
|
||||
|
||||
it("listCategories 能够统计分类列表与端点总数", async () => {
|
||||
const cats = await listCategories();
|
||||
expect(cats.length).toBeGreaterThanOrEqual(10);
|
||||
const corpCat = cats.find((c) => c.name === "企业通讯录");
|
||||
expect(corpCat).toBeDefined();
|
||||
expect(corpCat?.count).toBeGreaterThan(0);
|
||||
expect(corpCat?.endpointsCount).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,250 @@
|
||||
import embeddedCatalog from "../../../specs/docs-catalog.json" with { type: "json" };
|
||||
import { getGlobalCache } from "../../core/cache/index.js";
|
||||
import { fetchLiveDocsCatalog } from "./api.js";
|
||||
import type {
|
||||
DocCatalog,
|
||||
DocCategoryInfo,
|
||||
DocSearchQuery,
|
||||
DocSearchResult,
|
||||
OpenApiDocItem,
|
||||
} from "./types.js";
|
||||
|
||||
const CACHE_KEY = "docs:catalog:v1";
|
||||
const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24小时缓存
|
||||
|
||||
/**
|
||||
* 获取接口文档目录(具备实时拉取 + L1/L2 缓存 + 静态内嵌保底能力)
|
||||
*/
|
||||
export async function getDocsCatalog(options?: {
|
||||
forceRefresh?: boolean;
|
||||
baseUrl?: string;
|
||||
}): Promise<DocCatalog> {
|
||||
const cache = getGlobalCache();
|
||||
|
||||
if (!options?.forceRefresh) {
|
||||
const cached = cache.get<DocCatalog>(CACHE_KEY, "docs");
|
||||
if (cached && Array.isArray(cached.items) && cached.items.length > 0) {
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
// 尝试从线上获取最新规范
|
||||
try {
|
||||
const liveCatalog = await fetchLiveDocsCatalog({ baseUrl: options?.baseUrl });
|
||||
cache.set(CACHE_KEY, liveCatalog, {
|
||||
ttlMs: CACHE_TTL_MS,
|
||||
namespace: "docs",
|
||||
});
|
||||
return liveCatalog;
|
||||
} catch (error) {
|
||||
// 若强制刷新失败且存在历史缓存,则返回历史缓存
|
||||
const cached = cache.get<DocCatalog>(CACHE_KEY, "docs");
|
||||
if (cached && Array.isArray(cached.items) && cached.items.length > 0) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
// 线上无法连通且无历史缓存时,安全降级至本地内嵌预编译规格
|
||||
return embeddedCatalog as unknown as DocCatalog;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算文档项与搜索关键词的相关度得分
|
||||
*/
|
||||
function scoreDocItem(item: OpenApiDocItem, queryLower: string): number {
|
||||
let score = 0;
|
||||
const pathLower = (item.path || "").toLowerCase();
|
||||
const titleLower = item.title.toLowerCase();
|
||||
const categoryLower = item.category.toLowerCase();
|
||||
const urlLower = item.url.toLowerCase();
|
||||
|
||||
// 路径完全匹配
|
||||
if (pathLower === queryLower) score += 100;
|
||||
else if (pathLower.includes(queryLower)) score += 60;
|
||||
|
||||
// 标题完全匹配或包含
|
||||
if (titleLower === queryLower) score += 80;
|
||||
else if (titleLower.includes(queryLower)) score += 40;
|
||||
|
||||
// 分类完全匹配或包含
|
||||
if (categoryLower === queryLower) score += 50;
|
||||
else if (categoryLower.includes(queryLower)) score += 20;
|
||||
|
||||
// URL 路径包含
|
||||
if (urlLower.includes(queryLower)) score += 30;
|
||||
|
||||
// CURL 或参数定义中出现
|
||||
if (item.curl && item.curl.toLowerCase().includes(queryLower)) score += 25;
|
||||
if (item.parameters && item.parameters.toLowerCase().includes(queryLower)) score += 20;
|
||||
|
||||
// 正文段落包含
|
||||
for (const s of item.sections) {
|
||||
if (s.content.toLowerCase().includes(queryLower)) {
|
||||
score += 10;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索开放平台接口与指南文档
|
||||
*/
|
||||
export async function searchDocs(
|
||||
query: DocSearchQuery = {},
|
||||
options?: { forceRefresh?: boolean; baseUrl?: string }
|
||||
): Promise<DocSearchResult> {
|
||||
const catalog = await getDocsCatalog(options);
|
||||
let items = catalog.items;
|
||||
|
||||
// 1. 分类过滤
|
||||
if (query.category) {
|
||||
const catLower = query.category.trim().toLowerCase();
|
||||
items = items.filter((item) =>
|
||||
item.category.toLowerCase().includes(catLower)
|
||||
);
|
||||
}
|
||||
|
||||
// 2. HTTP 方法过滤
|
||||
if (query.method) {
|
||||
const methodUpper = query.method.trim().toUpperCase();
|
||||
items = items.filter((item) => item.method === methodUpper);
|
||||
}
|
||||
|
||||
// 3. 接口路径匹配过滤
|
||||
if (query.path) {
|
||||
const pathLower = query.path.trim().toLowerCase();
|
||||
items = items.filter((item) =>
|
||||
(item.path || "").toLowerCase().includes(pathLower)
|
||||
);
|
||||
}
|
||||
|
||||
// 4. 关键词打分与排序
|
||||
const rawKeyword = query.keyword?.trim();
|
||||
if (rawKeyword) {
|
||||
const keywordLower = rawKeyword.toLowerCase();
|
||||
const scored = items
|
||||
.map((item) => ({ item, score: scoreDocItem(item, keywordLower) }))
|
||||
.filter((entry) => entry.score > 0)
|
||||
.sort((a, b) => b.score - a.score);
|
||||
|
||||
items = scored.map((entry) => entry.item);
|
||||
}
|
||||
|
||||
const total = items.length;
|
||||
const limit = Math.max(1, Math.min(query.limit ?? 20, 100));
|
||||
const pagedItems = items.slice(0, limit);
|
||||
|
||||
return {
|
||||
total,
|
||||
keyword: rawKeyword,
|
||||
category: query.category,
|
||||
method: query.method,
|
||||
items: pagedItems,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 ID、Path、URL 或文档标题精确解析单篇文档详情
|
||||
*/
|
||||
export async function getDocDetail(
|
||||
target: string,
|
||||
options?: { forceRefresh?: boolean; baseUrl?: string }
|
||||
): Promise<OpenApiDocItem | undefined> {
|
||||
const catalog = await getDocsCatalog(options);
|
||||
const cleanTarget = target.trim();
|
||||
if (!cleanTarget) return undefined;
|
||||
|
||||
const targetLower = cleanTarget.toLowerCase();
|
||||
|
||||
// 1. 按数字 ID 精确查找
|
||||
const idNum = Number(cleanTarget);
|
||||
if (!Number.isNaN(idNum)) {
|
||||
const byId = catalog.items.find((item) => item.id === idNum);
|
||||
if (byId) return byId;
|
||||
}
|
||||
|
||||
// 2. 按接口 Path 精确查找 (如 /api/openapi/v1/roleDefGroups)
|
||||
const byExactPath = catalog.items.find(
|
||||
(item) => (item.path || "").toLowerCase() === targetLower
|
||||
);
|
||||
if (byExactPath) return byExactPath;
|
||||
|
||||
// 3. 按文档 URL 精确查找 (如 /docs/open-api/corporation/get-roles-group)
|
||||
const byExactUrl = catalog.items.find(
|
||||
(item) => item.url.toLowerCase() === targetLower
|
||||
);
|
||||
if (byExactUrl) return byExactUrl;
|
||||
|
||||
// 4. 按标题精确查找
|
||||
const byExactTitle = catalog.items.find(
|
||||
(item) => item.title.toLowerCase() === targetLower
|
||||
);
|
||||
if (byExactTitle) return byExactTitle;
|
||||
|
||||
// 5. 模糊前缀/子串匹配(取最相似的第一个)
|
||||
return (
|
||||
catalog.items.find((item) => (item.path || "").toLowerCase().includes(targetLower)) ||
|
||||
catalog.items.find((item) => item.url.toLowerCase().includes(targetLower)) ||
|
||||
catalog.items.find((item) => item.title.toLowerCase().includes(targetLower))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取开放平台所有业务模块分类与文档数量汇总
|
||||
*/
|
||||
export async function listCategories(options?: {
|
||||
forceRefresh?: boolean;
|
||||
baseUrl?: string;
|
||||
}): Promise<DocCategoryInfo[]> {
|
||||
const catalog = await getDocsCatalog(options);
|
||||
const map = new Map<string, { count: number; endpointsCount: number }>();
|
||||
|
||||
for (const item of catalog.items) {
|
||||
const cat = item.category || "未分类";
|
||||
const current = map.get(cat) || { count: 0, endpointsCount: 0 };
|
||||
current.count += 1;
|
||||
if (item.method && item.path) {
|
||||
current.endpointsCount += 1;
|
||||
}
|
||||
map.set(cat, current);
|
||||
}
|
||||
|
||||
const result: DocCategoryInfo[] = [];
|
||||
for (const [name, stats] of map.entries()) {
|
||||
result.push({
|
||||
name,
|
||||
count: stats.count,
|
||||
endpointsCount: stats.endpointsCount,
|
||||
});
|
||||
}
|
||||
|
||||
return result.sort((a, b) => b.count - a.count);
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动强制同步线上文档中心索引并重载本地持久化缓存
|
||||
*/
|
||||
export async function syncDocsCatalog(options?: {
|
||||
baseUrl?: string;
|
||||
}): Promise<{
|
||||
success: boolean;
|
||||
totalDocs: number;
|
||||
totalEndpoints: number;
|
||||
source: string;
|
||||
updatedAt: string;
|
||||
}> {
|
||||
const catalog = await getDocsCatalog({
|
||||
forceRefresh: true,
|
||||
baseUrl: options?.baseUrl,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
totalDocs: catalog.totalDocs,
|
||||
totalEndpoints: catalog.totalEndpoints,
|
||||
source: catalog.sourceUrl,
|
||||
updatedAt: catalog.updatedAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const DocSectionSchema = z.object({
|
||||
title: z.string().default("概述"),
|
||||
content: z.string().default(""),
|
||||
});
|
||||
|
||||
export const OpenApiDocItemSchema = z.object({
|
||||
id: z.number(),
|
||||
title: z.string().default(""),
|
||||
category: z.string().default("未分类"),
|
||||
url: z.string().default(""),
|
||||
permalink: z.string().default(""),
|
||||
method: z.string().optional(),
|
||||
path: z.string().optional(),
|
||||
breadcrumbs: z.array(z.string()).default([]),
|
||||
headings: z.array(z.string()).default([]),
|
||||
sections: z.array(DocSectionSchema).default([]),
|
||||
parameters: z.string().optional(),
|
||||
curl: z.string().optional(),
|
||||
responseSample: z.string().optional(),
|
||||
});
|
||||
|
||||
export const DocCatalogSchema = z.object({
|
||||
version: z.string().default("1.0.0"),
|
||||
updatedAt: z.string(),
|
||||
sourceUrl: z.string().default("https://docs.ekuaibao.com/search-index.json"),
|
||||
totalDocs: z.number(),
|
||||
totalEndpoints: z.number(),
|
||||
items: z.array(OpenApiDocItemSchema),
|
||||
});
|
||||
|
||||
export type DocSection = z.infer<typeof DocSectionSchema>;
|
||||
export type OpenApiDocItem = z.infer<typeof OpenApiDocItemSchema>;
|
||||
export type DocCatalog = z.infer<typeof DocCatalogSchema>;
|
||||
|
||||
export interface DocSearchQuery {
|
||||
keyword?: string;
|
||||
category?: string;
|
||||
method?: string;
|
||||
path?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface DocSearchResult {
|
||||
total: number;
|
||||
keyword?: string;
|
||||
category?: string;
|
||||
method?: string;
|
||||
items: OpenApiDocItem[];
|
||||
}
|
||||
|
||||
export interface DocCategoryInfo {
|
||||
name: string;
|
||||
count: number;
|
||||
endpointsCount: number;
|
||||
}
|
||||
Reference in new issue
Block a user