| | | 1 | | using Microsoft.OpenApi.Any; |
| | | 2 | | using Microsoft.OpenApi.Models; |
| | | 3 | | using Swashbuckle.AspNetCore.SwaggerGen; |
| | | 4 | | using TicTacToeApp.API.Response; |
| | | 5 | | |
| | | 6 | | namespace TicTacToeApp.API.Filters; |
| | | 7 | | |
| | | 8 | | // Фильтр для добавления примеров ErrorResponse |
| | | 9 | | public class ErrorResponseSchemaFilter : ISchemaFilter |
| | | 10 | | { |
| | | 11 | | public void Apply(OpenApiSchema schema, SchemaFilterContext context) |
| | | 12 | | { |
| | | 13 | | if (context.Type == typeof(ErrorResponse)) |
| | | 14 | | { |
| | | 15 | | schema.Example = new OpenApiObject |
| | | 16 | | { |
| | | 17 | | ["statusCode"] = new OpenApiString("400"), |
| | | 18 | | ["message"] = new OpenApiString("Invalid request"), |
| | | 19 | | ["detail"] = new OpenApiString("The 'id' parameter must be a positive number") |
| | | 20 | | }; |
| | | 21 | | } |
| | | 22 | | } |
| | | 23 | | } |
| | | 24 | | |
| | | 25 | | |
| | | 26 | | public class ErrorResponseOperationFilter : IOperationFilter |
| | | 27 | | { |
| | | 28 | | public void Apply(OpenApiOperation operation, OperationFilterContext context) |
| | | 29 | | { |
| | 0 | 30 | | var statusCodes = new Dictionary<string, (string Message, string Detail)> |
| | 0 | 31 | | { |
| | 0 | 32 | | ["400"] = ("Invalid request", "The 'id' parameter must be a positive number"), |
| | 0 | 33 | | ["404"] = ("Resource not found", "The requested resource was not found"), |
| | 0 | 34 | | ["409"] = ("Conflict", "Поле занято"), |
| | 0 | 35 | | ["412"] = ("Precondition failed", "Несогласованное состояние объекта Game"), |
| | 0 | 36 | | ["500"] = ("Internal server error", "An unexpected error occurred") |
| | 0 | 37 | | }; |
| | | 38 | | |
| | 0 | 39 | | foreach (var (code, (message, detail)) in statusCodes) |
| | | 40 | | { |
| | 0 | 41 | | if (operation.Responses.TryGetValue(code, out var response) && |
| | 0 | 42 | | response.Content.TryGetValue("application/json", out var mediaType)) |
| | | 43 | | { |
| | 0 | 44 | | mediaType.Example = new OpenApiObject |
| | 0 | 45 | | { |
| | 0 | 46 | | ["statusCode"] = new OpenApiInteger(int.Parse(code)), |
| | 0 | 47 | | ["message"] = new OpenApiString(message), |
| | 0 | 48 | | ["detail"] = new OpenApiString(detail) |
| | 0 | 49 | | }; |
| | | 50 | | } |
| | | 51 | | } |
| | 0 | 52 | | } |
| | | 53 | | } |