DecodeLifeCycle.java 1.57 KB
package com.topdraw.dockingapi.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.lifecycles.MethodAnnotationLifeCycle;
import com.dtflys.forest.reflection.ForestMethod;
import com.topdraw.dockingapi.util.DecryptUtils;
import lombok.SneakyThrows;

/**
 * @author wenxin
 * @version 1.0
 * @date 2024/5/28 下午2:46
 */
public class DecodeLifeCycle implements MethodAnnotationLifeCycle<Decode, Object> {


    @Override
    public void onMethodInitialized(ForestMethod method, Decode annotation) {

    }

    @SneakyThrows
    @Override
    @SuppressWarnings("all")
    public void onSuccess(Object data, ForestRequest request, ForestResponse response) {
        String value = (String) getAttribute(request, "value");
        String content = response.getContent();
        ForestMethod<?> method = request.getMethod();
        Class<?> returnClass = method.getReturnClass();
        JSONObject responseData = JSON.parseObject(content, JSONObject.class);
        if (StrUtil.isNotBlank(responseData.getString("errcode"))) {
            data = BeanUtil.copyProperties(responseData, returnClass);
        } else {
            String encrypt = responseData.getString("encrypt");
            String bodyJson = DecryptUtils.decode(value, encrypt);
            data = BeanUtil.copyProperties(JSONObject.parseObject(bodyJson), returnClass);
        }
        response.setResult(data);
    }
}