|
| 1 | +package it.aboutbits.springboot.toolbox.swagger.customization.error_response; |
| 2 | + |
| 3 | +import io.swagger.v3.core.converter.ModelConverters; |
| 4 | +import io.swagger.v3.oas.models.OpenAPI; |
| 5 | +import io.swagger.v3.oas.models.media.Content; |
| 6 | +import io.swagger.v3.oas.models.media.MediaType; |
| 7 | +import io.swagger.v3.oas.models.media.Schema; |
| 8 | +import io.swagger.v3.oas.models.responses.ApiResponse; |
| 9 | +import io.swagger.v3.oas.models.responses.ApiResponses; |
| 10 | +import it.aboutbits.springboot.toolbox.mvc.response.ErrorResponse; |
| 11 | +import org.springdoc.core.customizers.OpenApiCustomizer; |
| 12 | + |
| 13 | +import java.util.Map; |
| 14 | + |
| 15 | +public class ErrorCustomizer implements OpenApiCustomizer { |
| 16 | + @Override |
| 17 | + public void customise(OpenAPI openApi) { |
| 18 | + openApi.getComponents() |
| 19 | + .getSchemas() |
| 20 | + .putAll( |
| 21 | + ModelConverters.getInstance().read(ErrorResponse.class) |
| 22 | + ); |
| 23 | + |
| 24 | + var errorResponseSchema = openApi.getComponents().getSchemas().get("ErrorResponse"); |
| 25 | + @SuppressWarnings("unchecked") |
| 26 | + Map<String, Schema<?>> props = errorResponseSchema.getProperties(); |
| 27 | + for (var prop : props.values()) { |
| 28 | + prop.nullable(true); |
| 29 | + } |
| 30 | + |
| 31 | + openApi.getPaths() |
| 32 | + .values() |
| 33 | + .forEach( |
| 34 | + pathItem -> pathItem.readOperations() |
| 35 | + .forEach( |
| 36 | + operation -> { |
| 37 | + ApiResponses apiResponses = operation.getResponses(); |
| 38 | + apiResponses.addApiResponse( |
| 39 | + "400", |
| 40 | + createApiResponse( |
| 41 | + "Bad Request", |
| 42 | + errorResponseSchema |
| 43 | + ) |
| 44 | + ); |
| 45 | + apiResponses.addApiResponse( |
| 46 | + "404", |
| 47 | + createApiResponse( |
| 48 | + "Not Found", |
| 49 | + errorResponseSchema |
| 50 | + ) |
| 51 | + ); |
| 52 | + } |
| 53 | + ) |
| 54 | + ); |
| 55 | + } |
| 56 | + |
| 57 | + private ApiResponse createApiResponse(String message, Schema<?> schema) { |
| 58 | + var mediaType = new MediaType(); |
| 59 | + mediaType.schema(schema); |
| 60 | + return new ApiResponse().description(message) |
| 61 | + .content(new Content().addMediaType( |
| 62 | + org.springframework.http.MediaType.APPLICATION_JSON_VALUE, |
| 63 | + mediaType |
| 64 | + )); |
| 65 | + } |
| 66 | +} |
0 commit comments