WebResult.java 2.52 KB
package com.dituhui.pea.pojo;


import com.dituhui.pea.enums.StatusCodeEnum;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * 结果封装类
 * @author zl
 *
 */
@Data
@Accessors(chain = true)
public class WebResult<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 成功标志
     */
    private Boolean success;

    /**
     * 消息
     */
    private String message;

    /**
     * 返回代码
     */
    private String code;

    /**
     * 请求轨迹id
     */
    private String traceId;

    /**
     * 时间戳
     */
    private Long timestamp = System.currentTimeMillis();

    /**
     * 结果对象
     */
    private T result;

    public static <T> WebResult<T> ok() {
        return restResult(StatusCodeEnum.SUCCESS, null);
    }

    public static <T> WebResult<T> ok(T result) {
        return restResult(StatusCodeEnum.SUCCESS, result);
    }


    public static <T> WebResult<T> failed() {
        return restResult(StatusCodeEnum.FAILED, null);
    }

    public static <T> WebResult<T> failed(T result, String code, String msg, Boolean success) {
        return restResult(result, code, msg, success);
    }

    public static <T> WebResult<T> failed(StatusCodeEnum codeEnum) {
        return restResult(codeEnum, null);
    }

    private static <T> WebResult<T> restResult(StatusCodeEnum codeEnum, T result) {
        WebResult<T> apiResult = new WebResult<>();
        apiResult.setResult(result);
        // 用户信息
        PlatformUser platformUser = CurrentUser.threadPlatformUser.get();
        if (null != platformUser) {
            apiResult.setTraceId(platformUser.getIdLog());
        }
        apiResult.setCode(codeEnum.getCode());
        apiResult.setMessage(codeEnum.getDesc());
        apiResult.setTimestamp(System.currentTimeMillis());
        apiResult.setSuccess(codeEnum.getSuccess());
        return apiResult;
    }

    private static <T> WebResult<T> restResult(T result, String code, String msg, Boolean success) {
        WebResult<T> apiResult = new WebResult<>();
        apiResult.setResult(result);
        // 用户信息
        PlatformUser platformUser = CurrentUser.threadPlatformUser.get();
        if (null != platformUser) {
            apiResult.setTraceId(platformUser.getIdLog());
        }
        apiResult.setCode(code);
        apiResult.setMessage(msg);
        apiResult.setTimestamp(System.currentTimeMillis());
        apiResult.setSuccess(success);
        return apiResult;
    }


}