文章

过滤接口数据功能

过滤接口数据功能

框架已经实现动态过滤掉返回对象的字段和包含指定字段的功能,本次使用的demo例子所在位置如下图

26-1


1.过滤接口数据功能

已实现在返回前端的接口结果中,根据配置来指定只显示某些字段来给前端展示的功能。

在controller的方法中使用Filter注解,结果返回时自动过滤exclude中配置的字段,即返回数据对象中配置的对应字段自动不显示。其中type为需要排除字段所在对象的class。

以查询所有数据的list方法为例:

不使用注解时:

1
2
3
4
5
6
@Operation(description = "查询所有数据")
@RequestMapping(value = "/list", method = RequestMethod.POST)
public List<Test> list(@RequestBody(required = false) Test test) {
  List<Test> result = myBaseService.list(new QueryWrapper(test));
  return result;
}

返回值为:

26-2


使用注解后:

1
2
3
4
5
6
7
8
9
10
11
@Filter(
    rules = {
      @Rule(
          type = Test.class,
          exclude = {"description"})
    })
@Operation(description = "查询所有数据并过滤description字段")
@RequestMapping(value = "/filter", method = RequestMethod.POST)
public List<Test> testExclude() {
  return myBaseService.list();
}

返回结果为:

26-3

通过配置exclude后,返回结果中,已自动去除配置的description字段。


2.包含指定字段

有的时候只想给前端返回指定的字段,如果实体字段太多的话,用exclude就需要加上很多字段,操作起来不太方便,这时就可以使用include方法,指定返回的字段。

使用示例如下

1
2
3
4
5
6
7
8
9
10
11
@Filter(
    rules = {
      @Rule(
          type = Test.class,
          include = {"description"})
    })
@Operation(description = "查询所有数据并只返回description字段")
@RequestMapping(value = "/include", method = RequestMethod.POST)
public List<Test> testInclude() {
  return myBaseService.list();
}

返回结果如下,只返回指定的description字段

26-4


3.多层级过滤的复杂用法

如果有更复杂过滤需求,例如返回值是对象嵌套的形式,想同时对所有层级的对象进行过滤。框架支持rules属性里写多个规则,并且规则支持include和exclude混搭。

值得注意的是多个规则的添加顺序可以任意,exclude/include会找到所有层级下的所有的对象进行过滤,exclude/include的顺序并不会影响最后的查询结果。

以分页查询字典的接口为例,如果不用注解,返回结果如下:

26-5

在方法上加上注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Filter(
    rules = {
      @Rule(
          type = Dicset.class,
          exclude = {"code", "name"}),
      @Rule(
          type = MyPage.class,
          include = {"records"})
    })
@Operation(description = "分页查询数据")
@RequestMapping(value = "/pageList", method = RequestMethod.POST)
public MyPage<Dicset> pageList(@RequestBody Dicset dicset) {
  MyPage<Dicset> page = new MyPage<>(dicset.getCurrentPage(), dicset.getPageSize());
  MyPage<Dicset> result = dicsetService.myPage(page, new QueryWrapper(dicset));
  return result;
}

返回结果:

26-6

可以看到返回结果中只包含了MyPage对象中的records属性,并且把DicSet对象的code和name属性过滤掉了。

本文由作者按照 CC BY 4.0 进行授权