feat: 添加接口管理功能(后端OpenAPI解析入库+前端列表/详情/测试)
- 新增 ApiEndpoint/ApiParam 实体和 Mapper - 新增 DTO 层(分页查询请求、列表项、详情项、参数项、代理测试请求/响应) - 新增 ApiEndpointService 含 OpenAPI JSON 解析、\ 展开(最大10层)、分页查询 - 新增 ApiEndpointSyncRunner 启动时异步同步 - 新增 ApiEndpointController 分页/详情/手动同步接口 - 新增 ApiTestProxyController 代理测试接口(SSRF 防护) - 前端新增接口列表页、详情弹窗(含测试面板、Token 来源选择) - 前端新增菜单和路由
This commit is contained in:
@@ -0,0 +1,65 @@
|
|||||||
|
package com.emotion.controller;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
import com.emotion.common.PageResult;
|
||||||
|
import com.emotion.common.Result;
|
||||||
|
import com.emotion.dto.request.ApiEndpointListRequest;
|
||||||
|
import com.emotion.dto.response.ApiEndpointDetailResponse;
|
||||||
|
import com.emotion.dto.response.ApiEndpointItemResponse;
|
||||||
|
import com.emotion.service.ApiEndpointService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import javax.validation.Valid;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接口端点控制器
|
||||||
|
*
|
||||||
|
* @author Peanut
|
||||||
|
* @date 2026-05-23
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/admin/endpoint")
|
||||||
|
@Tag(name = "接口管理", description = "接口发现、同步和测试")
|
||||||
|
public class ApiEndpointController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ApiEndpointService apiEndpointService;
|
||||||
|
|
||||||
|
@Operation(summary = "分页查询接口列表", description = "支持关键词、方法、标签过滤")
|
||||||
|
@PostMapping("/list")
|
||||||
|
public Result<PageResult<ApiEndpointItemResponse>> list(@Valid @RequestBody ApiEndpointListRequest request) {
|
||||||
|
IPage<ApiEndpointItemResponse> page = apiEndpointService.getPage(request);
|
||||||
|
PageResult<ApiEndpointItemResponse> result = new PageResult<>(page);
|
||||||
|
return Result.success(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "查询接口详情", description = "返回接口详情和参数列表")
|
||||||
|
@GetMapping("/detail")
|
||||||
|
public Result<ApiEndpointDetailResponse> detail(@RequestParam String operationId) {
|
||||||
|
ApiEndpointDetailResponse response = apiEndpointService.getDetail(operationId);
|
||||||
|
if (response == null) {
|
||||||
|
return Result.notFound("接口不存在");
|
||||||
|
}
|
||||||
|
return Result.success(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "手动触发同步", description = "异步执行,返回 taskId")
|
||||||
|
@PostMapping("/sync")
|
||||||
|
public Result<Map<String, String>> sync() {
|
||||||
|
Map<String, String> result = new HashMap<>();
|
||||||
|
result.put("taskId", "sync-" + System.currentTimeMillis());
|
||||||
|
new Thread(() -> {
|
||||||
|
try {
|
||||||
|
apiEndpointService.syncFromOpenApi();
|
||||||
|
} catch (Exception e) {
|
||||||
|
// 异常已在 service 层记录
|
||||||
|
}
|
||||||
|
}).start();
|
||||||
|
return Result.success("同步任务已提交", result);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
package com.emotion.controller;
|
||||||
|
|
||||||
|
import com.emotion.common.Result;
|
||||||
|
import com.emotion.dto.request.ApiTestProxyRequest;
|
||||||
|
import com.emotion.dto.response.ApiTestProxyResponse;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.http.*;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
import org.springframework.web.client.HttpClientErrorException;
|
||||||
|
import org.springframework.web.client.HttpServerErrorException;
|
||||||
|
import org.springframework.web.client.ResourceAccessException;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import javax.validation.Valid;
|
||||||
|
import java.net.SocketTimeoutException;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接口代理测试控制器
|
||||||
|
* 仅允许转发到 /api/* 路径,避免 SSRF
|
||||||
|
*
|
||||||
|
* @author Peanut
|
||||||
|
* @date 2026-05-23
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/admin/endpoint")
|
||||||
|
@Tag(name = "接口管理", description = "接口测试代理")
|
||||||
|
public class ApiTestProxyController {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(ApiTestProxyController.class);
|
||||||
|
private static final int DEFAULT_TIMEOUT = 30;
|
||||||
|
private static final int MAX_RAW_BODY_LENGTH = 2000;
|
||||||
|
|
||||||
|
@Value("${server.port:19089}")
|
||||||
|
private int serverPort;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private RestTemplate restTemplate;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
@Operation(summary = "代理测试请求", description = "转发请求到本地后端并返回响应")
|
||||||
|
@PostMapping("/test")
|
||||||
|
public Result<ApiTestProxyResponse> test(@Valid @RequestBody ApiTestProxyRequest request) {
|
||||||
|
if (!request.getPath().startsWith("/api/")) {
|
||||||
|
return Result.error("仅允许代理 /api/* 路径的请求");
|
||||||
|
}
|
||||||
|
|
||||||
|
String url = "http://127.0.0.1:" + serverPort + request.getPath();
|
||||||
|
int timeout = request.getTimeoutSeconds() != null ? request.getTimeoutSeconds() : DEFAULT_TIMEOUT;
|
||||||
|
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
if (request.getHeaders() != null) {
|
||||||
|
for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
|
||||||
|
headers.set(entry.getKey(), entry.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Append query params to URL if present
|
||||||
|
if (request.getParams() != null && !request.getParams().isEmpty()) {
|
||||||
|
StringBuilder sb = new StringBuilder(url);
|
||||||
|
sb.append("?");
|
||||||
|
for (Map.Entry<String, String> entry : request.getParams().entrySet()) {
|
||||||
|
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
|
||||||
|
}
|
||||||
|
url = sb.substring(0, sb.length() - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
Object body = null;
|
||||||
|
if (request.getBody() != null && !request.getBody().isBlank()) {
|
||||||
|
try {
|
||||||
|
body = objectMapper.readValue(request.getBody(), Object.class);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return Result.error("请求体 JSON 格式错误: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
HttpMethod httpMethod = HttpMethod.valueOf(request.getMethod().toUpperCase());
|
||||||
|
HttpEntity<Object> entity = new HttpEntity<>(body, headers);
|
||||||
|
|
||||||
|
long startTime = System.currentTimeMillis();
|
||||||
|
ApiTestProxyResponse response = new ApiTestProxyResponse();
|
||||||
|
|
||||||
|
try {
|
||||||
|
ResponseEntity<String> rawResponse = restTemplate.exchange(url, httpMethod, entity, String.class);
|
||||||
|
long duration = System.currentTimeMillis() - startTime;
|
||||||
|
|
||||||
|
response.setStatus(rawResponse.getStatusCodeValue());
|
||||||
|
response.setDuration(duration);
|
||||||
|
|
||||||
|
try {
|
||||||
|
response.setBody(objectMapper.readValue(rawResponse.getBody(), Object.class));
|
||||||
|
} catch (Exception e) {
|
||||||
|
String rawBody = rawResponse.getBody();
|
||||||
|
if (rawBody != null && rawBody.length() > MAX_RAW_BODY_LENGTH) {
|
||||||
|
rawBody = rawBody.substring(0, MAX_RAW_BODY_LENGTH) + "\n... (已截断)";
|
||||||
|
}
|
||||||
|
if (rawBody != null) {
|
||||||
|
rawBody = rawBody.replace("<", "<").replace(">", ">");
|
||||||
|
}
|
||||||
|
response.setRawBody(rawBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, String> respHeaders = new HashMap<>();
|
||||||
|
for (String key : rawResponse.getHeaders().keySet()) {
|
||||||
|
respHeaders.put(key, rawResponse.getHeaders().getFirst(key));
|
||||||
|
}
|
||||||
|
response.setHeaders(respHeaders);
|
||||||
|
|
||||||
|
return Result.success(response);
|
||||||
|
|
||||||
|
} catch (ResourceAccessException e) {
|
||||||
|
long duration = System.currentTimeMillis() - startTime;
|
||||||
|
if (e.getCause() instanceof SocketTimeoutException) {
|
||||||
|
return Result.error("代理请求超时(" + timeout + "s),目标接口可能响应过慢或不可达");
|
||||||
|
}
|
||||||
|
return Result.error("代理请求失败: " + e.getMessage());
|
||||||
|
} catch (HttpClientErrorException | HttpServerErrorException e) {
|
||||||
|
long duration = System.currentTimeMillis() - startTime;
|
||||||
|
response.setStatus(e.getStatusCode().value());
|
||||||
|
response.setDuration(duration);
|
||||||
|
String rawBody = e.getResponseBodyAsString();
|
||||||
|
if (rawBody.length() > MAX_RAW_BODY_LENGTH) {
|
||||||
|
rawBody = rawBody.substring(0, MAX_RAW_BODY_LENGTH) + "\n... (已截断)";
|
||||||
|
}
|
||||||
|
response.setRawBody(rawBody.replace("<", "<").replace(">", ">"));
|
||||||
|
return Result.success(response);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return Result.error("代理请求失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package com.emotion.dto.request;
|
||||||
|
|
||||||
|
import com.emotion.common.BasePageRequest;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接口端点分页查询请求
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = true)
|
||||||
|
public class ApiEndpointListRequest extends BasePageRequest {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTP 方法过滤:GET/POST/PUT/DELETE/PATCH
|
||||||
|
*/
|
||||||
|
private String method;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 标签过滤
|
||||||
|
*/
|
||||||
|
private String tags;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否仅显示废弃接口
|
||||||
|
*/
|
||||||
|
private Integer deprecated;
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package com.emotion.dto.request;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import javax.validation.constraints.NotBlank;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 代理测试请求参数
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class ApiTestProxyRequest {
|
||||||
|
|
||||||
|
@NotBlank(message = "请求方法不能为空")
|
||||||
|
private String method;
|
||||||
|
|
||||||
|
@NotBlank(message = "接口路径不能为空")
|
||||||
|
private String path;
|
||||||
|
|
||||||
|
private String body;
|
||||||
|
|
||||||
|
private Map<String, String> headers;
|
||||||
|
|
||||||
|
private Map<String, String> params;
|
||||||
|
|
||||||
|
private Integer timeoutSeconds;
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package com.emotion.dto.response;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接口端点详情响应
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class ApiEndpointDetailResponse {
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
private String path;
|
||||||
|
private String method;
|
||||||
|
private String operationId;
|
||||||
|
private String summary;
|
||||||
|
private String description;
|
||||||
|
private String tags;
|
||||||
|
private Integer deprecated;
|
||||||
|
private String requestSchema;
|
||||||
|
private String responseSchema;
|
||||||
|
private String createTime;
|
||||||
|
private List<ApiParamItemResponse> params;
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package com.emotion.dto.response;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接口端点列表项
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class ApiEndpointItemResponse {
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
private String path;
|
||||||
|
private String method;
|
||||||
|
private String summary;
|
||||||
|
private String tags;
|
||||||
|
private Integer deprecated;
|
||||||
|
private String createTime;
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.emotion.dto.response;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接口参数详情项
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class ApiParamItemResponse {
|
||||||
|
|
||||||
|
private String paramType;
|
||||||
|
private String name;
|
||||||
|
private Integer required;
|
||||||
|
private String paramTypeDef;
|
||||||
|
private String description;
|
||||||
|
private String defaultValue;
|
||||||
|
private String enumValues;
|
||||||
|
private String example;
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package com.emotion.dto.response;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 代理测试响应
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class ApiTestProxyResponse {
|
||||||
|
|
||||||
|
private int status;
|
||||||
|
private Object body;
|
||||||
|
private Map<String, String> headers;
|
||||||
|
private long duration;
|
||||||
|
private String rawBody;
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.emotion.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import com.emotion.common.BaseEntity;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.experimental.SuperBuilder;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接口端点实体,继承 BaseEntity 字段
|
||||||
|
*
|
||||||
|
* @author Peanut
|
||||||
|
* @date 2026-05-23
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = true)
|
||||||
|
@SuperBuilder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@TableName("api_endpoint")
|
||||||
|
public class ApiEndpoint extends BaseEntity {
|
||||||
|
|
||||||
|
@TableField("path")
|
||||||
|
private String path;
|
||||||
|
|
||||||
|
@TableField("method")
|
||||||
|
private String method;
|
||||||
|
|
||||||
|
@TableField("operation_id")
|
||||||
|
private String operationId;
|
||||||
|
|
||||||
|
@TableField("summary")
|
||||||
|
private String summary;
|
||||||
|
|
||||||
|
@TableField("description")
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
@TableField("tags")
|
||||||
|
private String tags;
|
||||||
|
|
||||||
|
@TableField("deprecated")
|
||||||
|
private Integer deprecated;
|
||||||
|
|
||||||
|
@TableField("request_schema")
|
||||||
|
private String requestSchema;
|
||||||
|
|
||||||
|
@TableField("response_schema")
|
||||||
|
private String responseSchema;
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.emotion.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import com.emotion.common.BaseEntity;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.experimental.SuperBuilder;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接口参数实体
|
||||||
|
*
|
||||||
|
* @author Peanut
|
||||||
|
* @date 2026-05-23
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = true)
|
||||||
|
@SuperBuilder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@TableName("api_param")
|
||||||
|
public class ApiParam extends BaseEntity {
|
||||||
|
|
||||||
|
@TableField("endpoint_id")
|
||||||
|
private String endpointId;
|
||||||
|
|
||||||
|
@TableField("param_type")
|
||||||
|
private String paramType;
|
||||||
|
|
||||||
|
@TableField("name")
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@TableField("required")
|
||||||
|
private Integer required;
|
||||||
|
|
||||||
|
@TableField("param_type_def")
|
||||||
|
private String paramTypeDef;
|
||||||
|
|
||||||
|
@TableField("description")
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
@TableField("default_value")
|
||||||
|
private String defaultValue;
|
||||||
|
|
||||||
|
@TableField("enum_values")
|
||||||
|
private String enumValues;
|
||||||
|
|
||||||
|
@TableField("example")
|
||||||
|
private String example;
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.emotion.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.emotion.entity.ApiEndpoint;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接口端点 Mapper
|
||||||
|
*/
|
||||||
|
@Mapper
|
||||||
|
public interface ApiEndpointMapper extends BaseMapper<ApiEndpoint> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.emotion.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.emotion.entity.ApiParam;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接口参数 Mapper
|
||||||
|
*/
|
||||||
|
@Mapper
|
||||||
|
public interface ApiParamMapper extends BaseMapper<ApiParam> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.emotion.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
import com.emotion.dto.request.ApiEndpointListRequest;
|
||||||
|
import com.emotion.dto.response.ApiEndpointDetailResponse;
|
||||||
|
import com.emotion.dto.response.ApiEndpointItemResponse;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接口端点服务
|
||||||
|
*
|
||||||
|
* @author Peanut
|
||||||
|
* @date 2026-05-23
|
||||||
|
*/
|
||||||
|
public interface ApiEndpointService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分页查询接口列表
|
||||||
|
*/
|
||||||
|
IPage<ApiEndpointItemResponse> getPage(ApiEndpointListRequest request);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询接口详情(含参数)
|
||||||
|
*/
|
||||||
|
ApiEndpointDetailResponse getDetail(String operationId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从 OpenAPI spec 同步接口数据
|
||||||
|
*/
|
||||||
|
void syncFromOpenApi();
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.emotion.service;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.ApplicationArguments;
|
||||||
|
import org.springframework.boot.ApplicationRunner;
|
||||||
|
import org.springframework.scheduling.annotation.Async;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动时自动同步接口数据
|
||||||
|
*
|
||||||
|
* @author Peanut
|
||||||
|
* @date 2026-05-23
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class ApiEndpointSyncRunner implements ApplicationRunner {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(ApiEndpointSyncRunner.class);
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ApiEndpointService apiEndpointService;
|
||||||
|
|
||||||
|
@Async
|
||||||
|
@Override
|
||||||
|
public void run(ApplicationArguments args) throws Exception {
|
||||||
|
log.info("启动同步:开始异步同步接口数据");
|
||||||
|
try {
|
||||||
|
apiEndpointService.syncFromOpenApi();
|
||||||
|
log.info("启动同步:接口数据同步完成");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("启动同步:接口数据同步失败: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,331 @@
|
|||||||
|
package com.emotion.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.emotion.dto.request.ApiEndpointListRequest;
|
||||||
|
import com.emotion.dto.response.ApiEndpointDetailResponse;
|
||||||
|
import com.emotion.dto.response.ApiEndpointItemResponse;
|
||||||
|
import com.emotion.dto.response.ApiParamItemResponse;
|
||||||
|
import com.emotion.entity.ApiEndpoint;
|
||||||
|
import com.emotion.entity.ApiParam;
|
||||||
|
import com.emotion.mapper.ApiEndpointMapper;
|
||||||
|
import com.emotion.mapper.ApiParamMapper;
|
||||||
|
import com.emotion.service.ApiEndpointService;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接口端点服务实现
|
||||||
|
*
|
||||||
|
* @author Peanut
|
||||||
|
* @date 2026-05-23
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class ApiEndpointServiceImpl implements ApiEndpointService {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(ApiEndpointServiceImpl.class);
|
||||||
|
private static final int MAX_REF_DEPTH = 10;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ApiEndpointMapper endpointMapper;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ApiParamMapper paramMapper;
|
||||||
|
|
||||||
|
@Value("${server.port:19089}")
|
||||||
|
private int serverPort;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private RestTemplate restTemplate;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public IPage<ApiEndpointItemResponse> getPage(ApiEndpointListRequest request) {
|
||||||
|
Page<ApiEndpoint> page = new Page<>(request.getCurrent(), request.getSize());
|
||||||
|
LambdaQueryWrapper<ApiEndpoint> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
|
||||||
|
if (StringUtils.hasText(request.getKeyword())) {
|
||||||
|
wrapper.and(w -> w.like(ApiEndpoint::getPath, request.getKeyword())
|
||||||
|
.or().like(ApiEndpoint::getSummary, request.getKeyword())
|
||||||
|
.or().like(ApiEndpoint::getOperationId, request.getKeyword()));
|
||||||
|
}
|
||||||
|
if (StringUtils.hasText(request.getMethod())) {
|
||||||
|
wrapper.eq(ApiEndpoint::getMethod, request.getMethod());
|
||||||
|
}
|
||||||
|
if (StringUtils.hasText(request.getTags())) {
|
||||||
|
wrapper.like(ApiEndpoint::getTags, request.getTags());
|
||||||
|
}
|
||||||
|
if (request.getDeprecated() != null) {
|
||||||
|
wrapper.eq(ApiEndpoint::getDeprecated, request.getDeprecated());
|
||||||
|
}
|
||||||
|
|
||||||
|
wrapper.orderByDesc(ApiEndpoint::getCreateTime);
|
||||||
|
|
||||||
|
IPage<ApiEndpoint> result = endpointMapper.selectPage(page, wrapper);
|
||||||
|
return result.convert(this::toItemResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ApiEndpointDetailResponse getDetail(String operationId) {
|
||||||
|
LambdaQueryWrapper<ApiEndpoint> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
wrapper.eq(ApiEndpoint::getOperationId, operationId);
|
||||||
|
ApiEndpoint endpoint = endpointMapper.selectOne(wrapper);
|
||||||
|
if (endpoint == null) return null;
|
||||||
|
|
||||||
|
ApiEndpointDetailResponse response = toDetailResponse(endpoint);
|
||||||
|
|
||||||
|
LambdaQueryWrapper<ApiParam> paramWrapper = new LambdaQueryWrapper<>();
|
||||||
|
paramWrapper.eq(ApiParam::getEndpointId, endpoint.getId());
|
||||||
|
paramWrapper.orderByAsc(ApiParam::getName);
|
||||||
|
List<ApiParam> params = paramMapper.selectList(paramWrapper);
|
||||||
|
response.setParams(params.stream().map(this::toParamItemResponse).toList());
|
||||||
|
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public void syncFromOpenApi() {
|
||||||
|
String url = "http://127.0.0.1:" + serverPort + "/api/v3/api-docs";
|
||||||
|
log.info("开始同步接口数据,URL: {}", url);
|
||||||
|
|
||||||
|
String json;
|
||||||
|
try {
|
||||||
|
json = restTemplate.getForObject(url, String.class);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("获取 OpenAPI spec 失败: {}", e.getMessage());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (json == null || json.isBlank()) {
|
||||||
|
log.warn("OpenAPI spec 为空");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
JsonNode root = objectMapper.readTree(json);
|
||||||
|
JsonNode components = root.path("components");
|
||||||
|
JsonNode schemas = components.path("schemas");
|
||||||
|
|
||||||
|
paramMapper.delete(null);
|
||||||
|
endpointMapper.delete(null);
|
||||||
|
log.info("已清空旧接口数据");
|
||||||
|
|
||||||
|
JsonNode paths = root.path("paths");
|
||||||
|
Iterator<Map.Entry<String, JsonNode>> pathEntries = paths.fields();
|
||||||
|
int count = 0;
|
||||||
|
|
||||||
|
while (pathEntries.hasNext()) {
|
||||||
|
Map.Entry<String, JsonNode> pathEntry = pathEntries.next();
|
||||||
|
String path = pathEntry.getKey();
|
||||||
|
JsonNode methods = pathEntry.getValue();
|
||||||
|
|
||||||
|
for (Iterator<String> it = methods.fieldNames(); it.hasNext(); ) {
|
||||||
|
String method = it.next().toUpperCase();
|
||||||
|
// Skip non-HTTP-method keys (e.g., summary, description at path level)
|
||||||
|
if (!isHttpMethod(method)) continue;
|
||||||
|
|
||||||
|
JsonNode endpointNode = methods.get(method);
|
||||||
|
|
||||||
|
String operationId = endpointNode.path("operationId").asText();
|
||||||
|
if (operationId.isEmpty()) continue;
|
||||||
|
|
||||||
|
ApiEndpoint apiEndpoint = ApiEndpoint.builder()
|
||||||
|
.path(path)
|
||||||
|
.method(method)
|
||||||
|
.operationId(operationId)
|
||||||
|
.summary(endpointNode.path("summary").asText(null))
|
||||||
|
.description(endpointNode.path("description").asText(null))
|
||||||
|
.deprecated(endpointNode.path("deprecated").asBoolean(false) ? 1 : 0)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
JsonNode tagsNode = endpointNode.path("tags");
|
||||||
|
if (tagsNode.isArray() && tagsNode.size() > 0) {
|
||||||
|
List<String> tagList = new ArrayList<>();
|
||||||
|
for (JsonNode t : tagsNode) tagList.add(t.asText());
|
||||||
|
apiEndpoint.setTags(String.join(",", tagList));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse parameters
|
||||||
|
List<ApiParam> paramList = new ArrayList<>();
|
||||||
|
JsonNode parameters = endpointNode.path("parameters");
|
||||||
|
if (parameters.isArray()) {
|
||||||
|
for (JsonNode param : parameters) {
|
||||||
|
ApiParam apiParam = parseParam(param, schemas, 0);
|
||||||
|
if (apiParam != null) {
|
||||||
|
paramList.add(apiParam);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse requestBody schema
|
||||||
|
JsonNode requestBody = endpointNode.path("requestBody");
|
||||||
|
if (!requestBody.isMissingNode()) {
|
||||||
|
JsonNode content = requestBody.path("content");
|
||||||
|
if (!content.isMissingNode()) {
|
||||||
|
apiEndpoint.setRequestSchema(resolveSchema(content, schemas, 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse responses schema
|
||||||
|
JsonNode responses = endpointNode.path("responses");
|
||||||
|
if (!responses.isMissingNode()) {
|
||||||
|
apiEndpoint.setResponseSchema(responses.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
endpointMapper.insert(apiEndpoint);
|
||||||
|
|
||||||
|
for (ApiParam p : paramList) {
|
||||||
|
p.setEndpointId(apiEndpoint.getId());
|
||||||
|
paramMapper.insert(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("同步完成,共同步 {} 个接口", count);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("同步接口数据失败", e);
|
||||||
|
throw new RuntimeException("同步接口数据失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isHttpMethod(String method) {
|
||||||
|
return method.equals("GET") || method.equals("POST") || method.equals("PUT")
|
||||||
|
|| method.equals("DELETE") || method.equals("PATCH")
|
||||||
|
|| method.equals("HEAD") || method.equals("OPTIONS");
|
||||||
|
}
|
||||||
|
|
||||||
|
private ApiParam parseParam(JsonNode paramNode, JsonNode schemas, int depth) {
|
||||||
|
if (depth > MAX_REF_DEPTH) return null;
|
||||||
|
|
||||||
|
String name = paramNode.path("name").asText(null);
|
||||||
|
if (name == null) return null;
|
||||||
|
|
||||||
|
JsonNode schemaNode = paramNode.path("schema");
|
||||||
|
String typeDef = schemaNode.path("type").asText(null);
|
||||||
|
|
||||||
|
// Parse enum values if present
|
||||||
|
String enumValues = null;
|
||||||
|
JsonNode enumArray = schemaNode.path("enum");
|
||||||
|
if (enumArray.isArray() && enumArray.size() > 0) {
|
||||||
|
List<String> values = new ArrayList<>();
|
||||||
|
for (JsonNode v : enumArray) values.add(v.asText());
|
||||||
|
enumValues = String.join(",", values);
|
||||||
|
}
|
||||||
|
|
||||||
|
String defaultValue = schemaNode.path("default").asText(null);
|
||||||
|
|
||||||
|
return ApiParam.builder()
|
||||||
|
.paramType(paramNode.path("in").asText(null))
|
||||||
|
.name(name)
|
||||||
|
.required(paramNode.path("required").asBoolean(false) ? 1 : 0)
|
||||||
|
.paramTypeDef(typeDef)
|
||||||
|
.description(paramNode.path("description").asText(null))
|
||||||
|
.defaultValue(defaultValue)
|
||||||
|
.enumValues(enumValues)
|
||||||
|
.example(paramNode.path("example").asText(null))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String resolveSchema(JsonNode content, JsonNode schemas, int depth) {
|
||||||
|
if (depth > MAX_REF_DEPTH) return "{}";
|
||||||
|
|
||||||
|
JsonNode appJson = content.path("application/json");
|
||||||
|
if (appJson.isMissingNode()) return "{}";
|
||||||
|
|
||||||
|
JsonNode schema = appJson.path("schema");
|
||||||
|
return expandRef(schema, schemas, depth);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String expandRef(JsonNode node, JsonNode schemas, int depth) {
|
||||||
|
if (depth > MAX_REF_DEPTH) return "{\"$ref\": \"max depth exceeded\"}";
|
||||||
|
|
||||||
|
if (node.has("$ref")) {
|
||||||
|
String ref = node.path("$ref").asText();
|
||||||
|
if (ref.startsWith("#/components/schemas/")) {
|
||||||
|
String schemaName = ref.substring("#/components/schemas/".length());
|
||||||
|
JsonNode schemaNode = schemas.path(schemaName);
|
||||||
|
if (!schemaNode.isMissingNode()) {
|
||||||
|
return expandRef(schemaNode, schemas, depth + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "{\"$ref\": \"" + ref + "\"}";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (node.has("properties")) {
|
||||||
|
JsonNode props = node.path("properties");
|
||||||
|
StringBuilder sb = new StringBuilder("{");
|
||||||
|
boolean first = true;
|
||||||
|
for (Iterator<Map.Entry<String, JsonNode>> it = props.fields(); it.hasNext(); ) {
|
||||||
|
Map.Entry<String, JsonNode> entry = it.next();
|
||||||
|
if (!first) sb.append(",");
|
||||||
|
first = false;
|
||||||
|
sb.append("\"").append(entry.getKey()).append("\":")
|
||||||
|
.append(expandRef(entry.getValue(), schemas, depth + 1));
|
||||||
|
}
|
||||||
|
sb.append("}");
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
return node.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ApiEndpointItemResponse toItemResponse(ApiEndpoint e) {
|
||||||
|
ApiEndpointItemResponse r = new ApiEndpointItemResponse();
|
||||||
|
r.setId(e.getId());
|
||||||
|
r.setPath(e.getPath());
|
||||||
|
r.setMethod(e.getMethod());
|
||||||
|
r.setSummary(e.getSummary());
|
||||||
|
r.setTags(e.getTags());
|
||||||
|
r.setDeprecated(e.getDeprecated());
|
||||||
|
r.setCreateTime(e.getCreateTime() != null ? e.getCreateTime().toString() : null);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ApiEndpointDetailResponse toDetailResponse(ApiEndpoint e) {
|
||||||
|
ApiEndpointDetailResponse r = new ApiEndpointDetailResponse();
|
||||||
|
r.setId(e.getId());
|
||||||
|
r.setPath(e.getPath());
|
||||||
|
r.setMethod(e.getMethod());
|
||||||
|
r.setOperationId(e.getOperationId());
|
||||||
|
r.setSummary(e.getSummary());
|
||||||
|
r.setDescription(e.getDescription());
|
||||||
|
r.setTags(e.getTags());
|
||||||
|
r.setDeprecated(e.getDeprecated());
|
||||||
|
r.setRequestSchema(e.getRequestSchema());
|
||||||
|
r.setResponseSchema(e.getResponseSchema());
|
||||||
|
r.setCreateTime(e.getCreateTime() != null ? e.getCreateTime().toString() : null);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ApiParamItemResponse toParamItemResponse(ApiParam p) {
|
||||||
|
ApiParamItemResponse r = new ApiParamItemResponse();
|
||||||
|
r.setParamType(p.getParamType());
|
||||||
|
r.setName(p.getName());
|
||||||
|
r.setRequired(p.getRequired());
|
||||||
|
r.setParamTypeDef(p.getParamTypeDef());
|
||||||
|
r.setDescription(p.getDescription());
|
||||||
|
r.setDefaultValue(p.getDefaultValue());
|
||||||
|
r.setEnumValues(p.getEnumValues());
|
||||||
|
r.setExample(p.getExample());
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import request from '@/utils/request'
|
||||||
|
|
||||||
|
export interface ApiEndpointItem {
|
||||||
|
id: string
|
||||||
|
path: string
|
||||||
|
method: string
|
||||||
|
summary: string
|
||||||
|
tags: string
|
||||||
|
deprecated: number
|
||||||
|
createTime: string
|
||||||
|
operationId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiParamItem {
|
||||||
|
paramType: string
|
||||||
|
name: string
|
||||||
|
required: number
|
||||||
|
paramTypeDef: string
|
||||||
|
description: string
|
||||||
|
defaultValue: string
|
||||||
|
enumValues: string
|
||||||
|
example: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiEndpointDetail {
|
||||||
|
id: string
|
||||||
|
path: string
|
||||||
|
method: string
|
||||||
|
operationId: string
|
||||||
|
summary: string
|
||||||
|
description: string
|
||||||
|
tags: string
|
||||||
|
deprecated: number
|
||||||
|
requestSchema: string
|
||||||
|
responseSchema: string
|
||||||
|
createTime: string
|
||||||
|
params: ApiParamItem[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiEndpointListRequest {
|
||||||
|
current: number
|
||||||
|
size: number
|
||||||
|
keyword?: string
|
||||||
|
method?: string
|
||||||
|
tags?: string
|
||||||
|
deprecated?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiTestProxyRequest {
|
||||||
|
method: string
|
||||||
|
path: string
|
||||||
|
body?: string
|
||||||
|
headers?: Record<string, string>
|
||||||
|
params?: Record<string, string>
|
||||||
|
timeoutSeconds?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiTestProxyResponse {
|
||||||
|
status: number
|
||||||
|
body?: any
|
||||||
|
headers?: Record<string, string>
|
||||||
|
duration: number
|
||||||
|
rawBody?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分页查询接口列表
|
||||||
|
*/
|
||||||
|
export function getEndpointList(data: ApiEndpointListRequest) {
|
||||||
|
return request.post('/admin/endpoint/list', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询接口详情
|
||||||
|
*/
|
||||||
|
export function getEndpointDetail(operationId: string) {
|
||||||
|
return request.get('/admin/endpoint/detail', { params: { operationId } })
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手动触发同步
|
||||||
|
*/
|
||||||
|
export function syncEndpoints() {
|
||||||
|
return request.post('/admin/endpoint/sync')
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 代理测试请求
|
||||||
|
*/
|
||||||
|
export function testEndpoint(data: ApiTestProxyRequest) {
|
||||||
|
return request.post('/admin/endpoint/test', data)
|
||||||
|
}
|
||||||
@@ -45,6 +45,10 @@ export const menuConfig: MenuItem[] = [
|
|||||||
{
|
{
|
||||||
path: '/tools/api-tester',
|
path: '/tools/api-tester',
|
||||||
title: 'API接口调用'
|
title: 'API接口调用'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/endpoint/list',
|
||||||
|
title: '接口管理'
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -107,6 +107,12 @@ const routes: RouteRecordRaw[] = [
|
|||||||
name: 'ApiTester',
|
name: 'ApiTester',
|
||||||
component: () => import('@/views/tools/ApiTester.vue'),
|
component: () => import('@/views/tools/ApiTester.vue'),
|
||||||
meta: { title: 'API接口调用' }
|
meta: { title: 'API接口调用' }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'list',
|
||||||
|
name: 'EndpointList',
|
||||||
|
component: () => import('@/views/endpoint/EndpointList.vue'),
|
||||||
|
meta: { title: '接口管理' }
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,235 @@
|
|||||||
|
<template>
|
||||||
|
<el-dialog v-model="visible" :title="'接口详情'" width="800px" destroy-on-close>
|
||||||
|
<el-tabs v-model="activeTab">
|
||||||
|
<!-- 详情标签 -->
|
||||||
|
<el-tab-pane label="详情" name="detail">
|
||||||
|
<template v-if="detail">
|
||||||
|
<el-descriptions :column="2" border>
|
||||||
|
<el-descriptions-item label="方法">
|
||||||
|
<el-tag :type="getMethodType(detail.method)">{{ detail.method }}</el-tag>
|
||||||
|
</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="路径">{{ detail.path }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="Operation ID">{{ detail.operationId }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="简述">{{ detail.summary || '-' }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="标签" :span="2">{{ detail.tags || '-' }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="描述" :span="2">{{ detail.description || '-' }}</el-descriptions-item>
|
||||||
|
</el-descriptions>
|
||||||
|
|
||||||
|
<!-- 参数列表 -->
|
||||||
|
<h4 v-if="detail.params && detail.params.length > 0" style="margin-top: 20px">参数列表</h4>
|
||||||
|
<el-table :data="detail.params" border size="small" style="margin-top: 8px">
|
||||||
|
<el-table-column prop="paramType" label="类型" width="80" />
|
||||||
|
<el-table-column prop="name" label="名称" width="120" />
|
||||||
|
<el-table-column prop="required" label="必填" width="60" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag v-if="row.required === 1" type="danger" size="small">是</el-tag>
|
||||||
|
<span v-else>-</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="paramTypeDef" label="数据类型" width="100" />
|
||||||
|
<el-table-column prop="description" label="描述" min-width="150" />
|
||||||
|
<el-table-column prop="example" label="示例" min-width="120" />
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<!-- 请求体结构 -->
|
||||||
|
<h4 v-if="detail.requestSchema && detail.requestSchema !== '{}'" style="margin-top: 20px">请求体结构</h4>
|
||||||
|
<pre v-if="detail.requestSchema && detail.requestSchema !== '{}'" class="schema-json">{{ formatJson(detail.requestSchema) }}</pre>
|
||||||
|
</template>
|
||||||
|
<el-empty v-else description="暂无数据" />
|
||||||
|
</el-tab-pane>
|
||||||
|
|
||||||
|
<!-- 测试标签 -->
|
||||||
|
<el-tab-pane label="测试" name="test">
|
||||||
|
<!-- Token 来源 -->
|
||||||
|
<el-card class="token-card" style="margin-bottom: 16px">
|
||||||
|
<template #header>Token 来源</template>
|
||||||
|
<el-radio-group v-model="tokenSource">
|
||||||
|
<el-radio value="admin">使用当前管理员Token</el-radio>
|
||||||
|
<el-radio value="manual">手动输入</el-radio>
|
||||||
|
</el-radio-group>
|
||||||
|
<el-input
|
||||||
|
v-if="tokenSource === 'manual'"
|
||||||
|
v-model="manualToken"
|
||||||
|
placeholder="Bearer eyJhbGci..."
|
||||||
|
style="margin-top: 8px"
|
||||||
|
/>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- 参数表单 -->
|
||||||
|
<el-card style="margin-bottom: 16px">
|
||||||
|
<template #header>参数配置</template>
|
||||||
|
<el-form :model="testForm" label-width="80px">
|
||||||
|
<el-form-item label="请求路径">
|
||||||
|
<el-input v-model="testForm.path" disabled />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="请求方法">
|
||||||
|
<el-input v-model="testForm.method" disabled />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item v-for="param in (detail?.params || [])" :key="param.name" :label="param.name">
|
||||||
|
<el-input v-model="testForm.params[param.name]" :placeholder="param.description || param.example || ''" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item v-if="['POST', 'PUT', 'PATCH'].includes(testForm.method)" label="请求体">
|
||||||
|
<el-input v-model="testForm.body" type="textarea" :rows="5" placeholder="JSON 格式" />
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<el-button type="primary" @click="handleTest" :loading="testing">发送请求</el-button>
|
||||||
|
|
||||||
|
<!-- 响应结果 -->
|
||||||
|
<el-card v-if="testResult" style="margin-top: 16px">
|
||||||
|
<template #header>
|
||||||
|
<div style="display: flex; justify-content: space-between">
|
||||||
|
<span>响应结果</span>
|
||||||
|
<div>
|
||||||
|
<el-tag :type="testResult.status >= 200 && testResult.status < 300 ? 'success' : 'danger'">
|
||||||
|
{{ testResult.status }}
|
||||||
|
</el-tag>
|
||||||
|
<el-tag type="info" style="margin-left: 8px">{{ testResult.duration }}ms</el-tag>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<pre class="response-body">{{ testResult.display }}</pre>
|
||||||
|
</el-card>
|
||||||
|
</el-tab-pane>
|
||||||
|
</el-tabs>
|
||||||
|
</el-dialog>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, watch } from 'vue'
|
||||||
|
import { testEndpoint, type ApiEndpointDetail } from '@/api/endpoint'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
modelValue: boolean
|
||||||
|
detail: ApiEndpointDetail | null
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
'update:modelValue': [value: boolean]
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const visible = computed({
|
||||||
|
get: () => props.modelValue,
|
||||||
|
set: (val: boolean) => emit('update:modelValue', val)
|
||||||
|
})
|
||||||
|
|
||||||
|
const activeTab = ref('detail')
|
||||||
|
const tokenSource = ref('admin')
|
||||||
|
const manualToken = ref('')
|
||||||
|
const testing = ref(false)
|
||||||
|
const testResult = ref<{ status: number; duration: number; display: string } | null>(null)
|
||||||
|
|
||||||
|
const testForm = ref({
|
||||||
|
path: '',
|
||||||
|
method: '',
|
||||||
|
params: {} as Record<string, string>,
|
||||||
|
body: ''
|
||||||
|
})
|
||||||
|
|
||||||
|
watch(() => props.detail, (ep) => {
|
||||||
|
if (ep) {
|
||||||
|
testForm.value.path = ep.path
|
||||||
|
testForm.value.method = ep.method
|
||||||
|
testForm.value.params = {}
|
||||||
|
testForm.value.body = ''
|
||||||
|
testResult.value = null
|
||||||
|
activeTab.value = 'detail'
|
||||||
|
}
|
||||||
|
}, { immediate: true })
|
||||||
|
|
||||||
|
const getMethodType = (method: string): string => {
|
||||||
|
const types: Record<string, string> = {
|
||||||
|
GET: 'success',
|
||||||
|
POST: 'primary',
|
||||||
|
PUT: 'warning',
|
||||||
|
DELETE: 'danger',
|
||||||
|
PATCH: 'info'
|
||||||
|
}
|
||||||
|
return types[method] || 'info'
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatJson = (jsonStr: string): string => {
|
||||||
|
try {
|
||||||
|
return JSON.stringify(JSON.parse(jsonStr), null, 2)
|
||||||
|
} catch {
|
||||||
|
return jsonStr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleTest = async () => {
|
||||||
|
testing.value = true
|
||||||
|
try {
|
||||||
|
const headers: Record<string, string> = {}
|
||||||
|
const token = tokenSource.value === 'admin'
|
||||||
|
? localStorage.getItem('adminToken')
|
||||||
|
: manualToken.value
|
||||||
|
if (token) {
|
||||||
|
headers['Authorization'] = token.startsWith('Bearer ') ? token : `Bearer ${token}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const queryParams: Record<string, string> = {}
|
||||||
|
for (const [key, value] of Object.entries(testForm.value.params)) {
|
||||||
|
if (value) queryParams[key] = value
|
||||||
|
}
|
||||||
|
|
||||||
|
const res: any = await testEndpoint({
|
||||||
|
method: testForm.value.method,
|
||||||
|
path: testForm.value.path,
|
||||||
|
body: testForm.value.body || undefined,
|
||||||
|
headers,
|
||||||
|
params: Object.keys(queryParams).length > 0 ? queryParams : undefined,
|
||||||
|
timeoutSeconds: 30
|
||||||
|
})
|
||||||
|
|
||||||
|
if (res.code === 200 && res.data) {
|
||||||
|
const data = res.data
|
||||||
|
testResult.value = {
|
||||||
|
status: data.status,
|
||||||
|
duration: data.duration,
|
||||||
|
display: data.rawBody || JSON.stringify(data.body, null, 2)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
testResult.value = {
|
||||||
|
status: 0,
|
||||||
|
duration: 0,
|
||||||
|
display: res.message || '请求失败'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
testResult.value = {
|
||||||
|
status: 0,
|
||||||
|
duration: 0,
|
||||||
|
display: e.message || '请求失败'
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
testing.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped lang="scss">
|
||||||
|
.response-body {
|
||||||
|
background: #1e1e1e;
|
||||||
|
color: #d4d4d4;
|
||||||
|
padding: 12px;
|
||||||
|
border-radius: 4px;
|
||||||
|
max-height: 400px;
|
||||||
|
overflow: auto;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-all;
|
||||||
|
font-family: 'Menlo', 'Monaco', monospace;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.schema-json {
|
||||||
|
background: #f5f7fa;
|
||||||
|
color: #333;
|
||||||
|
padding: 12px;
|
||||||
|
border-radius: 4px;
|
||||||
|
max-height: 300px;
|
||||||
|
overflow: auto;
|
||||||
|
font-family: 'Menlo', 'Monaco', monospace;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
<template>
|
||||||
|
<div class="endpoint-list">
|
||||||
|
<div class="page-header">
|
||||||
|
<h2>接口管理</h2>
|
||||||
|
<div class="header-actions">
|
||||||
|
<el-button type="primary" @click="handleSync" :loading="syncing">
|
||||||
|
<el-icon><Refresh /></el-icon> 手动同步
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 搜索栏 -->
|
||||||
|
<el-card class="search-card">
|
||||||
|
<el-form :model="searchForm" inline>
|
||||||
|
<el-form-item label="关键词">
|
||||||
|
<el-input
|
||||||
|
v-model="searchForm.keyword"
|
||||||
|
placeholder="路径/简述/operationId"
|
||||||
|
clearable
|
||||||
|
style="width: 200px"
|
||||||
|
@clear="handleSearch"
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="方法">
|
||||||
|
<el-select v-model="searchForm.method" placeholder="全部" clearable style="width: 100px" @change="handleSearch">
|
||||||
|
<el-option label="GET" value="GET" />
|
||||||
|
<el-option label="POST" value="POST" />
|
||||||
|
<el-option label="PUT" value="PUT" />
|
||||||
|
<el-option label="DELETE" value="DELETE" />
|
||||||
|
<el-option label="PATCH" value="PATCH" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item>
|
||||||
|
<el-button type="primary" @click="handleSearch">搜索</el-button>
|
||||||
|
<el-button @click="handleReset">重置</el-button>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- 接口列表 -->
|
||||||
|
<el-card class="table-card">
|
||||||
|
<el-table :data="tableData" v-loading="loading" stripe>
|
||||||
|
<el-table-column label="方法" width="90" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="getMethodType(row.method)" size="small">{{ row.method }}</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="path" label="路径" min-width="300" show-overflow-tooltip />
|
||||||
|
<el-table-column prop="summary" label="简述" min-width="200" show-overflow-tooltip />
|
||||||
|
<el-table-column prop="tags" label="标签" min-width="150" show-overflow-tooltip />
|
||||||
|
<el-table-column label="状态" width="80" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag v-if="row.deprecated === 1" type="danger" size="small">废弃</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="100" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button type="primary" link size="small" @click="showDetail(row)">详情</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<div class="pagination">
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="pagination.current"
|
||||||
|
v-model:page-size="pagination.size"
|
||||||
|
:page-sizes="[10, 20, 50]"
|
||||||
|
:total="pagination.total"
|
||||||
|
layout="total, sizes, prev, pager, next"
|
||||||
|
@size-change="loadData"
|
||||||
|
@current-change="loadData"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- 详情弹窗 -->
|
||||||
|
<EndpointDetailDialog v-model="detailVisible" :detail="selectedDetail" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, onMounted } from 'vue'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import { Refresh } from '@element-plus/icons-vue'
|
||||||
|
import { getEndpointList, syncEndpoints, getEndpointDetail, type ApiEndpointItem, type ApiEndpointDetail } from '@/api/endpoint'
|
||||||
|
import EndpointDetailDialog from './EndpointDetailDialog.vue'
|
||||||
|
|
||||||
|
const loading = ref(false)
|
||||||
|
const syncing = ref(false)
|
||||||
|
const detailVisible = ref(false)
|
||||||
|
const selectedDetail = ref<ApiEndpointDetail | null>(null)
|
||||||
|
|
||||||
|
const searchForm = reactive({
|
||||||
|
keyword: '',
|
||||||
|
method: '',
|
||||||
|
tags: ''
|
||||||
|
})
|
||||||
|
|
||||||
|
const tableData = ref<ApiEndpointItem[]>([])
|
||||||
|
const pagination = reactive({
|
||||||
|
current: 1,
|
||||||
|
size: 20,
|
||||||
|
total: 0
|
||||||
|
})
|
||||||
|
|
||||||
|
const loadData = async () => {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const res: any = await getEndpointList({
|
||||||
|
current: pagination.current,
|
||||||
|
size: pagination.size,
|
||||||
|
keyword: searchForm.keyword || undefined,
|
||||||
|
method: searchForm.method || undefined,
|
||||||
|
tags: searchForm.tags || undefined
|
||||||
|
})
|
||||||
|
tableData.value = res.data.records || []
|
||||||
|
pagination.total = res.data.total || 0
|
||||||
|
} catch (e: any) {
|
||||||
|
ElMessage.error('加载失败: ' + e.message)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSearch = () => {
|
||||||
|
pagination.current = 1
|
||||||
|
loadData()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleReset = () => {
|
||||||
|
searchForm.keyword = ''
|
||||||
|
searchForm.method = ''
|
||||||
|
searchForm.tags = ''
|
||||||
|
handleSearch()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSync = async () => {
|
||||||
|
syncing.value = true
|
||||||
|
try {
|
||||||
|
await syncEndpoints()
|
||||||
|
ElMessage.success('同步任务已提交,请稍后刷新查看结果')
|
||||||
|
setTimeout(() => loadData(), 5000)
|
||||||
|
} catch (e: any) {
|
||||||
|
ElMessage.error('同步失败: ' + e.message)
|
||||||
|
} finally {
|
||||||
|
syncing.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const showDetail = async (row: ApiEndpointItem) => {
|
||||||
|
selectedDetail.value = null
|
||||||
|
detailVisible.value = true
|
||||||
|
try {
|
||||||
|
const res: any = await getEndpointDetail(row.operationId)
|
||||||
|
selectedDetail.value = res.data
|
||||||
|
} catch {
|
||||||
|
ElMessage.error('加载详情失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getMethodType = (method: string): string => {
|
||||||
|
const types: Record<string, string> = {
|
||||||
|
GET: 'success',
|
||||||
|
POST: 'primary',
|
||||||
|
PUT: 'warning',
|
||||||
|
DELETE: 'danger',
|
||||||
|
PATCH: 'info'
|
||||||
|
}
|
||||||
|
return types[method] || 'info'
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => loadData())
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped lang="scss">
|
||||||
|
.endpoint-list {
|
||||||
|
.page-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
|
||||||
|
h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 20px;
|
||||||
|
color: var(--el-text-color-primary);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-card {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pagination {
|
||||||
|
margin-top: 16px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
Reference in New Issue
Block a user