registry/public/js/api.js

130 lines
3.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* API 调用封装
* 统一处理与后端 REST 接口的交互,返回解析后的数据或抛出错误
*/
const API = {
/**
* 通用请求方法
* @param {string} url - 请求路径
* @param {Object} options - fetch 选项
* @returns {Promise<any>} 响应数据
*/
async request(url, options = {}) {
const opts = {
headers: { "Content-Type": "application/json" },
...options,
};
if (opts.body && typeof opts.body !== "string") {
opts.body = JSON.stringify(opts.body);
}
const res = await fetch(url, opts);
const json = await res.json();
if (!json.success) {
throw new Error(json.message || "请求失败");
}
return json.data;
},
/**
* 获取所有项目
* @returns {Promise<Array>} 项目列表
*/
getProjects() {
return this.request("/api/projects");
},
/**
* 获取单个项目
* @param {string} id - 项目 ID
* @returns {Promise<Object>} 项目对象
*/
getProject(id) {
return this.request(`/api/projects/${id}`);
},
/**
* 创建项目
* @param {Object} data - 项目数据
* @returns {Promise<Object>} 创建的项目
*/
createProject(data) {
return this.request("/api/projects", { method: "POST", body: data });
},
/**
* 删除项目
* @param {string} id - 项目 ID
* @returns {Promise<void>}
*/
deleteProject(id) {
return this.request(`/api/projects/${id}`, { method: "DELETE" });
},
/**
* 更新项目维度映射方式
* @param {string} id - 项目 ID
* @param {Object} mappings - { idcMapping, environmentMapping, groupMapping }
* @returns {Promise<Object>} 更新后的项目
*/
updateMappings(id, mappings) {
return this.request(`/api/projects/${id}/mappings`, { method: "PUT", body: mappings });
},
/**
* 获取项目下所有配置
* @param {string} projectId - 项目 ID
* @returns {Promise<Array>} 配置项列表
*/
getConfigs(projectId) {
return this.request(`/api/projects/${projectId}/configs`);
},
/**
* 新增配置项
* @param {string} projectId - 项目 ID
* @param {Object} data - 配置项数据
* @returns {Promise<Object>} 创建的配置项
*/
createConfig(projectId, data) {
return this.request(`/api/projects/${projectId}/configs`, { method: "POST", body: data });
},
/**
* 更新配置项
* @param {string} projectId - 项目 ID
* @param {string} configId - 配置项 ID
* @param {Object} data - 要更新的字段
* @returns {Promise<Object>} 更新后的配置项
*/
updateConfig(projectId, configId, data) {
return this.request(`/api/projects/${projectId}/configs/${configId}`, { method: "PUT", body: data });
},
/**
* 删除配置项
* @param {string} projectId - 项目 ID
* @param {string} configId - 配置项 ID
* @returns {Promise<void>}
*/
deleteConfig(projectId, configId) {
return this.request(`/api/projects/${projectId}/configs/${configId}`, { method: "DELETE" });
},
/**
* 获取当前模式
* @returns {Promise<Object>} { mode }
*/
getMode() {
return this.request("/api/mode");
},
/**
* 切换模式
* @param {string} mode - 目标模式plan/edit/readonly
* @returns {Promise<Object>} { mode }
*/
setMode(mode) {
return this.request("/api/mode", { method: "PUT", body: { mode } });
},
};