14 lines
469 B
TypeScript
14 lines
469 B
TypeScript
export const JsonCodec = {
|
|
/** POST/PUT 的请求体直接用对象,让传输层序列化为 JSON */
|
|
encode<T = any>(obj: T): any {
|
|
return obj ?? {};
|
|
},
|
|
|
|
/** 根据传输层返回的类型做解码:string → JSON.parse,其他直接返回 */
|
|
decode<T = any>(resp: any): T {
|
|
if (typeof resp === "string") {
|
|
try { return JSON.parse(resp) as T; } catch { /* 可能是纯文本 */ }
|
|
}
|
|
return resp as T;
|
|
}
|
|
}; |