yapi-devloper-mcp
Version:
YApi MCP Integration
313 lines • 12 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.YApiService = exports.YApiError = void 0;
const axios_1 = __importStar(require("axios"));
class YApiError extends Error {
code;
response;
constructor(message, code, response) {
super(message);
this.code = code;
this.response = response;
this.name = 'YApiError';
}
}
exports.YApiError = YApiError;
class YApiService {
baseUrl;
token = null;
authConfig;
axiosInstance;
cookies = [];
constructor(baseUrl, authConfig) {
this.baseUrl = baseUrl;
this.authConfig = authConfig;
if (authConfig.type === 'token' && !authConfig.token) {
throw new Error('使用 token 认证时必须提供 token');
}
if (authConfig.type === 'password' && (!authConfig.username || !authConfig.password)) {
throw new Error('使用密码认证时必须提供用户名和密码');
}
if (authConfig.type === 'token') {
this.token = authConfig.token;
this.cookies = [authConfig.token];
}
this.axiosInstance = axios_1.default.create({
baseURL: baseUrl.replace(/\/$/, ''),
timeout: 10000,
});
this.axiosInstance.interceptors.response.use((response) => {
const setCookie = response.headers['set-cookie'];
if (setCookie) {
this.cookies = setCookie;
console.log('已保存新的 cookies');
}
return response;
}, (error) => {
return Promise.reject(error);
});
this.axiosInstance.interceptors.request.use((config) => {
if (this.cookies.length > 0) {
config.headers['Cookie'] = this.cookies.join('; ');
}
return config;
}, (error) => {
return Promise.reject(error);
});
this.axiosInstance.interceptors.request.use(this.requestLogger);
}
async login() {
if (this.authConfig.type === 'token') {
return;
}
try {
try {
const ldapResponse = await this.axiosInstance.post('/api/user/login_by_ldap', {
email: this.authConfig.username,
password: this.authConfig.password
});
if (ldapResponse.data.errcode === 0) {
this.token = ldapResponse.data.data.token;
console.log("LDAP 登录成功");
return;
}
}
catch (ldapError) {
console.log("LDAP 登录失败,尝试普通登录");
}
const normalResponse = await this.axiosInstance.post('/api/user/login', {
email: this.authConfig.username,
password: this.authConfig.password
});
if (normalResponse.data.errcode === 0) {
this.token = normalResponse.data.data.token;
console.log("普通登录成功");
return;
}
throw new Error(normalResponse.data.errmsg || "登录失败");
}
catch (error) {
if (error instanceof axios_1.AxiosError && error.response) {
console.error('所有登录方式都失败:', error.response.data);
throw new Error(`登录失败: ${error.response.data.errmsg || "未知错误"}`);
}
console.error('登录失败:', error);
throw new Error("与YApi服务器通信失败");
}
}
async ensureToken() {
if (!this.token) {
await this.login();
}
}
async request(endpoint, params = {}) {
await this.ensureToken();
try {
console.log(`调用 ${endpoint}`);
const response = await this.axiosInstance.get(endpoint, {
params: {
...params,
token: this.token
}
});
return response.data;
}
catch (error) {
if (error instanceof axios_1.AxiosError && error.response) {
if (error.response.status === 401 && this.authConfig.type === 'password') {
this.token = null;
await this.ensureToken();
return this.request(endpoint, params);
}
throw {
status: error.response.status,
message: error.response.data.errmsg || "未知错误",
};
}
throw new Error("与YApi服务器通信失败");
}
}
async getApiInterface(id) {
try {
const response = await this.request("/api/interface/get", { id });
if (response.errcode !== 0) {
throw new Error(response.errmsg || "获取API接口失败");
}
return response.data;
}
catch (error) {
console.error("获取API接口失败:", error);
throw error;
}
}
async createBasicInterface(data) {
await this.ensureToken();
try {
console.log(`创建基础接口: ${data.title}`);
const response = await this.axiosInstance.post("/api/interface/add", {
...data,
catid: Number(data.catid),
token: this.token
});
if (response.data.errcode !== 0) {
throw new YApiError(response.data.errmsg || "创建接口失败", response.data.errcode, response.data);
}
console.log('创建接口成功');
return response.data.data;
}
catch (error) {
if (error instanceof axios_1.AxiosError) {
if (error.response?.status === 401 && this.authConfig.type === 'password') {
this.token = null;
await this.ensureToken();
return this.createBasicInterface(data);
}
throw new YApiError(error.response?.data?.errmsg || "创建接口失败", error.response?.status || 500, error.response?.data);
}
if (error instanceof YApiError) {
throw error;
}
throw new YApiError("与YApi服务器通信失败", 500);
}
}
async updateInterfaceDetails(id, data) {
await this.ensureToken();
try {
console.log(`更新接口详情: ${id}`);
const defaultData = {
tag: [],
status: "undone",
switch_notice: true,
api_opened: false,
req_body_is_json_schema: true,
res_body_is_json_schema: true,
req_query: [],
req_headers: data.method !== 'POST' ? [
{
name: "Content-Type",
value: "application/x-www-form-urlencoded"
}
] : [
{
name: "Content-Type",
value: "application/json"
}
],
req_body_form: data.req_body_form || [],
req_params: [],
};
const mergedData = {
...defaultData,
...data
};
const response = await this.axiosInstance.post("/api/interface/up", {
id,
...mergedData,
token: this.token
});
if (response.data.errcode !== 0) {
throw new YApiError(response.data.errmsg || "更新接口失败", response.data.errcode, response.data);
}
console.log('更新接口成功');
return response.data.data;
}
catch (error) {
if (error instanceof axios_1.AxiosError) {
if (error.response?.status === 401 && this.authConfig.type === 'password') {
this.token = null;
await this.ensureToken();
return this.updateInterfaceDetails(id, data);
}
throw new YApiError(error.response?.data?.errmsg || "更新接口失败", error.response?.status || 500, error.response?.data);
}
if (error instanceof YApiError) {
throw error;
}
throw new YApiError("与YApi服务器通信失败", 500);
}
}
async createFullInterface(data) {
try {
const basicInterface = await this.createBasicInterface(data);
try {
console.log('创建基础接口成功');
const updatedInterface = await this.updateInterfaceDetails(basicInterface._id, data);
return updatedInterface;
}
catch (updateError) {
if (updateError instanceof YApiError) {
updateError.message = `接口已创建(ID: ${basicInterface._id}),但更新详情失败: ${updateError.message}`;
throw updateError;
}
throw new YApiError(`接口已创建(ID: ${basicInterface._id}),但更新详情失败`, 500, { basicInterface, updateError });
}
}
catch (error) {
if (error instanceof YApiError) {
throw error;
}
throw new YApiError(error instanceof Error ? error.message : "创建接口失败", 500, error);
}
}
async retryRequest(operation, maxRetries = 3) {
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
return await operation();
}
catch (error) {
lastError = error;
if (i < maxRetries - 1) {
await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, i)));
}
}
}
throw lastError;
}
requestLogger(config) {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] ${config.method.toUpperCase()} ${config.url}`);
return config;
}
handleError(error) {
if (error instanceof axios_1.AxiosError && error.response) {
throw new YApiError(error.response.data.errmsg || "请求失败", error.response.status, error.response.data);
}
throw new YApiError("网络错误", 500);
}
}
exports.YApiService = YApiService;
//# sourceMappingURL=yapi.js.map