优化 Springdoc Swagger 枚举显示

搭配 MybatisPlusIEnum 类型,优化枚举显示

修改前

修改前

修改后

修改后

EnumConverter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.annotation.IEnum;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.core.converter.AnnotatedType;
import io.swagger.v3.core.converter.ModelConverter;
import io.swagger.v3.core.converter.ModelConverterContext;
import io.swagger.v3.oas.models.media.Schema;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.providers.ObjectMapperProvider;
import org.springframework.stereotype.Component;

import java.util.Iterator;

@Component
@RequiredArgsConstructor
public class EnumConverter implements ModelConverter {

private final ObjectMapperProvider objectMapperProvider;

@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public Schema<?> resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
Schema<?> nextSchema = chain.hasNext() ? chain.next().resolve(type, context, chain) : null;
ObjectMapper objectMapper = objectMapperProvider.jsonMapper();
JavaType javaType = objectMapper.constructType(type.getType());
if (javaType != null && javaType.isEnumType()) {
Class<Enum> enumClass = (Class<Enum>) javaType.getRawClass();
Enum[] enums = enumClass.getEnumConstants();
StringBuilder builder = new StringBuilder();
for (Enum en : enums) {
if (en instanceof IEnum) {
var value = ReflectUtil.getFieldValue(en, "value");
var description = ReflectUtil.getFieldValue(en, "description");
builder.append(String.format("- %s: %s\n", Convert.toStr(value), Convert.toStr(description)));
}
}
if (nextSchema != null && !builder.isEmpty()) {
nextSchema.setTitle(nextSchema.getDescription());
nextSchema.setDescription(builder.toString());
}
}
return nextSchema;
}

}