51 lines
2.1 KiB
Plaintext
51 lines
2.1 KiB
Plaintext
/*
|
||
* Copyright (c) 2025 SimcuTeam. All rights reserved.
|
||
* 遵循 MIT 许可证。
|
||
*/
|
||
|
||
package simcu::simapi.helpers
|
||
|
||
import soulsoft_web_http.*
|
||
import soulsoft_web_mvc.core.*
|
||
import simcu::serialization.*
|
||
import simcu::simapi.communications.*
|
||
|
||
/**
|
||
* 统一响应封装工具。
|
||
* 供 SimApiRequestDelegateFactory 与内置路由委托复用:
|
||
* - SimApiBaseResponse(含子类)→ 原样输出
|
||
* - String → SimApiResponse<String>(data 为字符串)
|
||
* - Unit(void)→ SimApiBaseResponse()({code:200, message:成功})
|
||
* - 其他对象(DTO/数组/动态结构)→ SimApiDataResponse(data 内嵌为对象)
|
||
*
|
||
* 输出使用 simapi_serialization 序列化后直接写响应体(不走 soulsoft formatter)。
|
||
*/
|
||
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(含子类)→ 原样输出
|
||
writeJson(context, result)
|
||
} else if (let result: String <- actionResult) {
|
||
// String → SimApiResponse<String>(data 为字符串)
|
||
writeJson(context, SimApiResponse<String>(result))
|
||
} else if (let result: Unit <- actionResult) {
|
||
// void/无返回 → SimApiBaseResponse()({code:200, message:成功})
|
||
writeJson(context, SimApiBaseResponse())
|
||
} else {
|
||
// 其他对象(DTO/数组/动态结构)→ SimApiDataResponse
|
||
writeJson(context, SimApiDataResponse(actionResult))
|
||
}
|
||
}
|
||
|
||
/// simapi_serialization 序列化后直接写响应体(经 SimApiResponseWriter 缓存,供请求日志读取)
|
||
private static func writeJson(context: HttpContext, obj: Any): Unit {
|
||
context.response.contentType = "application/json; charset=utf-8"
|
||
SimApiResponseWriter.write(context, JsonSerializer.serialize(obj))
|
||
}
|
||
}
|