UNPKG

cis-api-tool

Version:

根据 swagger/yapi/apifox 的接口定义生成 TypeScript/JavaScript 的接口类型及其请求函数代码。

64 lines (58 loc) 1.87 kB
import axios from "axios"; //#region src/utils/apifox.ts /** * 从 Apifox 获取 OpenAPI 格式的数据 * @param config Apifox 配置 * @returns OpenAPI 文档 */ async function fetchApifoxOpenAPI(config) { const { serverUrl, token, projectId, exportOptions = { scope: { type: "ALL" }, options: { includeApifoxExtensionProperties: false, addFoldersToTags: true }, oasVersion: "3.1", exportFormat: "JSON" } } = config; if (!projectId) throw new Error("Apifox 项目 ID 是必需的"); let url; if (serverUrl.includes("/v1/projects/") && serverUrl.includes("/export-openapi")) url = serverUrl; else { const baseUrl = serverUrl.replace(/\/+$/, ""); url = `${baseUrl}/v1/projects/${projectId}/export-openapi`; } url += "?locale=zh-CN"; const headers = { "X-Apifox-Api-Version": "2024-03-28", "Authorization": `Bearer ${token}`, "Content-Type": "application/json" }; const requestBody = { scope: exportOptions.scope || { type: "ALL" }, options: exportOptions.options || { includeApifoxExtensionProperties: false, addFoldersToTags: true }, oasVersion: exportOptions.oasVersion || "3.1", exportFormat: exportOptions.exportFormat || "JSON" }; try { const response = await axios.post(url, requestBody, { headers, timeout: 3e4 }); if (response.status !== 200) throw new Error(`Apifox API 请求失败: ${response.status} ${response.statusText}`); const contentType = response.headers["content-type"] || ""; if (!contentType.includes("application/json")) throw new Error(`Apifox API 返回的不是JSON格式: ${contentType}`); return response.data; } catch (error) { if (axios.isAxiosError(error)) { const message = error.response?.data?.message || error.message; throw new Error(`Apifox API 请求失败: ${message}`); } throw error; } } //#endregion export { fetchApifoxOpenAPI };