2026-08-16 22:46:48 +08:00
|
|
|
|
/*
|
|
|
|
|
|
* Copyright (c) 2025 SimcuTeam. All rights reserved.
|
|
|
|
|
|
* 移植自 C# 项目 SimApi(E:\simcu\simapi-net),遵循 MIT 许可证。
|
|
|
|
|
|
*/
|
|
|
|
|
|
|
2026-08-18 04:23:07 +08:00
|
|
|
|
package simcu::simapi.helpers
|
2026-08-16 22:46:48 +08:00
|
|
|
|
|
|
|
|
|
|
import soulsoft_web_http.*
|
|
|
|
|
|
import soulsoft_web_mvc.core.*
|
2026-08-18 04:26:36 +08:00
|
|
|
|
import simcu::serialization.*
|
2026-08-18 04:23:07 +08:00
|
|
|
|
import simcu::simapi.communications.*
|
2026-08-16 22:46:48 +08:00
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 统一响应封装工具(对齐 C# SimApiResponseFilter 的包装分支)。
|
|
|
|
|
|
* 供 SimApiRequestDelegateFactory 与内置路由委托复用:
|
|
|
|
|
|
* - SimApiBaseResponse(含子类)→ 原样输出
|
|
|
|
|
|
* - String → SimApiResponse<String>(data 为字符串)
|
|
|
|
|
|
* - Unit(void)→ SimApiBaseResponse()({code:200, message:成功})
|
|
|
|
|
|
* - 其他对象(DTO/数组/动态结构)→ SimApiDataResponse(data 内嵌为对象)
|
2026-08-18 00:07:00 +08:00
|
|
|
|
*
|
|
|
|
|
|
* 输出使用 simapi_serialization 序列化后直接写响应体(不走 soulsoft formatter)。
|
2026-08-16 22:46:48 +08:00
|
|
|
|
*/
|
|
|
|
|
|
public class SimApiResultWriter {
|
|
|
|
|
|
private init() {}
|
|
|
|
|
|
|
|
|
|
|
|
public static func write(context: HttpContext, actionResult: Any): Unit {
|
|
|
|
|
|
if (let result: IActionResult <- actionResult) {
|
|
|
|
|
|
// 显式返回 IActionResult(如 ContentResult)→ 原样
|
|
|
|
|
|
result.invoke(context)
|
|
|
|
|
|
} else if (let result: SimApiBaseResponse <- actionResult) {
|
|
|
|
|
|
// 已是 SimApiBaseResponse(含子类)→ 原样输出
|
2026-08-18 00:07:00 +08:00
|
|
|
|
writeJson(context, result)
|
2026-08-16 22:46:48 +08:00
|
|
|
|
} else if (let result: String <- actionResult) {
|
|
|
|
|
|
// String → SimApiResponse<String>(data 为字符串)
|
2026-08-18 00:07:00 +08:00
|
|
|
|
writeJson(context, SimApiResponse<String>(result))
|
2026-08-16 22:46:48 +08:00
|
|
|
|
} else if (let result: Unit <- actionResult) {
|
|
|
|
|
|
// void/无返回 → SimApiBaseResponse()({code:200, message:成功})
|
2026-08-18 00:07:00 +08:00
|
|
|
|
writeJson(context, SimApiBaseResponse())
|
2026-08-16 22:46:48 +08:00
|
|
|
|
} else {
|
|
|
|
|
|
// 其他对象(DTO/数组/动态结构)→ SimApiDataResponse
|
2026-08-18 00:07:00 +08:00
|
|
|
|
writeJson(context, SimApiDataResponse(actionResult))
|
2026-08-16 22:46:48 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-08-18 00:07:00 +08:00
|
|
|
|
|
2026-08-18 02:43:11 +08:00
|
|
|
|
/// simapi_serialization 序列化后直接写响应体(经 SimApiResponseWriter 缓存,供请求日志读取)
|
2026-08-18 00:07:00 +08:00
|
|
|
|
private static func writeJson(context: HttpContext, obj: Any): Unit {
|
|
|
|
|
|
context.response.contentType = "application/json; charset=utf-8"
|
2026-08-18 02:43:11 +08:00
|
|
|
|
SimApiResponseWriter.write(context, JsonSerializer.Serialize(obj))
|
2026-08-18 00:07:00 +08:00
|
|
|
|
}
|
2026-08-16 22:46:48 +08:00
|
|
|
|
}
|