add ResponseEntity
parent
dce743d212
commit
dfc7c1ff8f
|
@ -0,0 +1,78 @@
|
|||
package cn.edu.hfut.rmdjzz.projectmanagement.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 用于包装响应体的实体类,静态调用用of方法实例化对象,例:<br/>
|
||||
* {@code return ResponseEntity.<User>of(HttpStatus.OK.value(),"查询成功!",result);}
|
||||
* @author 佘语殊
|
||||
* @since 2022/6/28 11:59
|
||||
*/
|
||||
@SuppressWarnings({"unchecked", "varargs"})
|
||||
@Data
|
||||
@AllArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class ResponseEntity<T> {
|
||||
private Integer code;
|
||||
private String msg;
|
||||
private QueryPage<T> data;
|
||||
|
||||
/**
|
||||
* 静态构造函数
|
||||
* @param <T> 数据类型
|
||||
* @param code 响应码
|
||||
* @param msg 响应消息
|
||||
* @param data 响应数据
|
||||
*/
|
||||
public static <T> ResponseEntity<T> of(Integer code, String msg, T... data) {
|
||||
return new ResponseEntity<>(code, msg, new QueryPage<>(data));
|
||||
}
|
||||
|
||||
public static <T> ResponseEntity<T> of(Integer code, String msg, Collection<T> data) {
|
||||
return new ResponseEntity<>(code, msg, new QueryPage<>(data));
|
||||
}
|
||||
|
||||
public static <T> ResponseEntity<T> of(Integer code, String msg, Page<T> data) {
|
||||
return new ResponseEntity<>(code, msg, new QueryPage<>(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* 响应体内部类,包装用于分页查询
|
||||
*/
|
||||
@Data
|
||||
private static class QueryPage<T> {
|
||||
private Long total;
|
||||
private List<T> records;
|
||||
|
||||
QueryPage(Page<T> data) {
|
||||
if (data == null) {
|
||||
this.records = new ArrayList<>();
|
||||
this.total = 0L;
|
||||
} else {
|
||||
this.records = data.getRecords();
|
||||
this.total = data.getTotal();
|
||||
}
|
||||
}
|
||||
|
||||
QueryPage(Collection<T> data) {
|
||||
if (data == null) {
|
||||
this.records = new ArrayList<>();
|
||||
this.total = 0L;
|
||||
} else {
|
||||
this.records = List.copyOf(data);
|
||||
this.total = (long) records.size();
|
||||
}
|
||||
}
|
||||
|
||||
QueryPage(T[] data) {
|
||||
//筛掉所有null
|
||||
this.records = Arrays.stream(data).filter(Objects::nonNull).collect(Collectors.toList());
|
||||
this.total = (long) records.size();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -13,6 +13,7 @@ class ProjectManagementTests {
|
|||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue