Decode.java 2.06 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.annotation.MethodLifeCycle;
import com.dtflys.forest.annotation.RequestAttributes;
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;

import java.lang.annotation.*;

/**
 * @author wenxin
 * @version 1.0
 * @date 2024/5/23 下午5:45
 */
@Documented
@MethodLifeCycle(Decode.DecodeLifeCycle.class)
@RequestAttributes
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
public @interface Decode {

    String value();

    class DecodeLifeCycle implements MethodAnnotationLifeCycle<Decode, Object> {
        private String key;

        @Override
        public void onMethodInitialized(ForestMethod method, Decode annotation) {
            this.key = annotation.value();
        }

        @SneakyThrows
        @Override
        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);
        }
    }
}