|
- package com.ningdatech.kqapi.common.model;
-
- import lombok.Data;
- import lombok.NoArgsConstructor;
-
- import java.io.Serializable;
-
- /**
- * <p>
- * ApiResponse - 统一的接口返回值封装
- * </p>
- *
- * @author WendyYang
- * @since 14:29 2022/9/29
- */
- @Data
- @NoArgsConstructor
- public class ApiResponse<T> implements Serializable {
- private static final long serialVersionUID = 532384723325394156L;
-
- public static final int SUCCESS_CODE = 200;
-
- public static final String SUCCESS_MSG = "success";
-
- public static final int ERROR_CODE = 500;
-
- public static final String ERROR_MSG = "Internal server error";
-
- /**
- * 状态码
- */
- private Integer code;
-
- /**
- * 返回内容
- */
- private String message;
-
- /**
- * 返回数据
- */
- private T data;
-
- /**
- * 全参构造函数
- *
- * @param code 状态码
- * @param message 返回内容
- * @param data 返回数据
- */
- private ApiResponse(Integer code, String message, T data) {
- this.code = code;
- this.message = message;
- this.data = data;
- }
-
- /**
- * 构造一个自定义的API返回
- *
- * @param code 状态码
- * @param message 返回内容
- * @param data 返回数据
- * @return ApiResponse
- */
- public static <T> ApiResponse<T> of(Integer code, String message, T data) {
- return new ApiResponse<T>(code, message, data);
- }
-
- public static <T> ApiResponse<T> of(Integer code, String message) {
- return of(code, message, null);
- }
-
- /**
- * 构造一个成功且不带数据的API返回
- *
- * @return ApiResponse
- */
- public static <T> ApiResponse<T> ofSuccess() {
- return ofSuccess(null);
- }
-
- /**
- * 构造一个成功且带数据的API返回
- *
- * @param data 返回数据
- * @return ApiResponse
- */
- public static <T> ApiResponse<T> ofSuccess(T data) {
- return ofStatus(Status.OK, data);
- }
-
- /**
- * 构造一个成功且自定义消息的API返回
- *
- * @param message 返回内容
- * @return ApiResponse
- */
- public static <T> ApiResponse<T> ofMessage(String message) {
- return of(Status.OK.getCode(), message, null);
- }
-
- /**
- * 构造一个有状态的API返回
- *
- * @param status 状态 {@link Status}
- * @return ApiResponse
- */
- public static <T> ApiResponse<T> ofStatus(ApiStatus status) {
- return ofStatus(status, null);
- }
-
- /**
- * 构造一个有状态且带数据的API返回
- *
- * @param status 状态 {@link Status}
- * @param data 返回数据
- * @return ApiResponse
- */
- public static <T> ApiResponse<T> ofStatus(ApiStatus status, T data) {
- return of(status.getCode(), status.getReasonPhrase(), data);
- }
-
- }
|