概况
网上大多文章是介绍有关magic-api的使用,但对应解决特定问题的方法却很少,由于自己是刚接触使用magicApi开发接口,很多地方遇到问题见网上搜不到,加上博主脑袋不是很灵光,一般要死磕一两个钟头才能够解决,常常体会这种痛苦,因此将自己的方法见解分享出来,希望能为有着相似问题的朋友提供一些帮助。
正文
起因
这个问题是来自业务需求,需要在分页返回的消息中加入一些分页的相关字段。
例如:
endRow:20 // 最后一条
firstPage:1 // 第一个页码
hasNextPage:true // 存在下页
hasPreviousPage:false // 存在上页
isFirstPage: true // 为第一页
isLastPage:false // 为最后一页
lastPage: 8 // 最后一个页码
而magic-api的分页方法返回的数据没有额外字段,所以需要手动计算
{
"data": {
"total": "3",
"list": [{
"id": "1701433288545034241",
"personName": "张三",
"personAge": "23",
"personGroup": "3",
"personPhone": "11111111111",
"createdBy": "1229349296795840514",
"createdTime": 1694488281000,
"updatedBy": null,
"updatedTime": null
},...]
},
"code": 0,
"msg": ""
}
int totalItemCount = listPage.total;
int totalPages = Math.ceil(totalItemCount / body.pageSize);
int endRow = (body.pageIndex * body.pageSize) > totalItemCount ? totalItemCount : (body.pageIndex * body.pageSize);
boolean hasNextPage = (body.pageIndex + 1) <= totalPages;
boolean hasPreviousPage = body.pageIndex > 1;
boolean isFirstPage = body.pageIndex == 1;
boolean isLastPage = !hasNextPage;
int firstPage = isFirstPage == true ? 1 : 0;
int lastPage = totalPages.asInt();
本以为写公式是这项工作稍微麻烦一些的地方,却不知将这些字段加入到data才是折磨。。
尝试
这里省略过程,无用的回忆就让它过去,防止大脑用错误案例来训练。
反反复复就是找不到方法这类的错误。
{
"data": null,
"code": 1,
"msg": "系统异常在java.util.ArrayList中找不到方法put(String,String) at Row:27~27,Col:5~16\n\nmap.put(\"1\",\"1\");\r\n ^^^^^^^^^^^^ "
}
{
"data": null,
"code": 1,
"msg": "系统异常在org.ssssssss.magicapi.modules.db.model.PageResult中找不到方法put(String,Long) at Row:30~30,Col:10~29\n\nlistPage.put(\"endRow\",endRow);\r\n ^^^^^^^^^^^^^^^^^^^^ "
}
{
"data": null,
"code": 1,
"msg": "系统异常在java.util.LinkedHashMap中找不到方法putAll(ArrayList) at Row:27~27,Col:3~16\n\na.putAll(result);\r\n ^^^^^^^^^^^^^^ "
}
解决
动物园的动物各归其所,大草原的生灵无拘无束
// 所用做的就是为这些参数重建一个map,全部装进来
var map = {};
map.put("endRow",endRow);
map.put("firstPage",firstPage);
map.put("hasNextPage",hasNextPage);
map.put("hasPreviousPage",hasPreviousPage);
map.put("isFirstPage",isFirstPage);
map.put("isLastPage",isLastPage);
map.put("lastPage",lastPage);
map.put("total",listPage.total);
// 别忘了分页数据
map.put("list",listPage.list);
让我们查看返回结果:成功!
{
"data": {
"endRow": "3",
"firstPage": 1,
"hasNextPage": false,
"hasPreviousPage": false,
"isFirstPage": true,
"isLastPage": true,
"lastPage": 0,
"total": "3",
"list": [{
"id": "1701433288545034241",
"personName": "张三",
"personAge": "23",
"personGroup": "3",
"personPhone": "11111111111",
"createdBy": "1229349296795840514",
"createdTime": 1694488281000,
"updatedBy": null,
"updatedTime": null
}, ...]
},
"code": 0,
"msg": ""
}
ps:magicApi对于一直用springboot开发接口的人真不适合,在我看来magic-api就是个四不像,语法杂糅,许多我熟悉的语法竟然莫名其妙报错,很难用!只是个人观点。
这个问题如果用spring框架就很好解决了,参考PageHelper教程springboot+mybatis+PageHelper附带返回值参数解析。
感谢观看,助大家学业有成步步高升。