Reputation: 163
We use Spring Boot and https://springdoc.org/ to generate OpenApi documentation. We want to change default schema for LocalDateTime, so we don't have the same annotation every time LocalDateTime is used. So, I added:
static {
SpringDocUtils.getConfig().replaceWithSchema(LocalDateTime.class,
new StringSchema().example("2021-07-05T10:35:17.000").pattern("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}[.]\\d{3}"));
}
it worked. The issue is that now it's impossible to add custom description or example for specific field:
@Schema(description = "important date")
private LocalDateTime aDate;
As you can see below description is missing in Swagger-UI: screenshot with missing description
Is it possible to fix? Is there another way to have default custom schema for LocalDateTime?
Upvotes: 1
Views: 3128
Reputation: 11
It's working with
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.7.0</version>
</dependency>
@Configuration
public class OpenApi3Config {
private static final String YYYY_MM_DD_T_HH_MM_SS_PATTERN = "yyyy-MM-dd'T'HH:mm:ss";
private static final String YYYY_MM_DD_PATTERN = "yyyy-MM-dd";
private static final String HH_MM_PATTERN = "HH:mm";
static {
StringSchema timeSchema = new StringSchema();
timeSchema.example(LocalTime.now().format(DateTimeFormatter.ofPattern(HH_MM_PATTERN)));
SpringDocUtils.getConfig().replaceWithSchema(LocalTime.class, timeSchema);
// Replace schema for LocalDate
StringSchema dateSchema = new StringSchema();
dateSchema.example(LocalDate.now().format(DateTimeFormatter.ofPattern(YYYY_MM_DD_PATTERN)));
SpringDocUtils.getConfig().replaceWithSchema(LocalDate.class, dateSchema);
// Replace schema for LocalDateTime
StringSchema datetimeSchema = new StringSchema();
datetimeSchema.example(LocalDateTime.now().format(DateTimeFormatter.ofPattern(YYYY_MM_DD_T_HH_MM_SS_PATTERN)));
SpringDocUtils.getConfig().replaceWithSchema(LocalDateTime.class, datetimeSchema);
}
}
Upvotes: 1
Reputation: 26
You could use OpenAPICustomerCustomiser
@Bean
public OpenApiCustomiser openAPICustomiser() {
return openApi -> {
openApi.getComponents().getSchemas().forEach((s, schema) -> {
Map<String, Schema> properties = schema.getProperties();
if (properties == null) {
properties = Map.of();
}
for (String propertyName : properties.keySet()) {
Schema propertySchema = properties.get(propertyName);
if (propertySchema instanceof DateTimeSchema) {
properties.replace(propertyName, new StringSchema()
.example("2021-07-05T10:35:17.000")
.pattern("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}[.]\\d{3}$")
//copies original description
.description(propertySchema.getDescription()));
}
}
});
};
}
Upvotes: 1