aboutsummaryrefslogtreecommitdiff
path: root/BackEnd/Timeline/Swagger/DocumentDescriptionDocumentProcessor.cs
blob: dc5ddd96924326e7c153de2dcbc202341a38c832 (plain)
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
48
49
50
51
52
53
54
55
using NSwag.Generation.Processors;
using NSwag.Generation.Processors.Contexts;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Timeline.Models.Http;

namespace Timeline.Swagger
{
    public class DocumentDescriptionDocumentProcessor : IDocumentProcessor
    {
        private static Dictionary<string, int> GetAllErrorCodes()
        {
            var errorCodes = new Dictionary<string, int>();

            void RecursiveCheckErrorCode(Type type)
            {
                foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
                    .Where(fi => fi.IsLiteral && !fi.IsInitOnly && fi.FieldType == typeof(int)))
                {
                    var name = (type.FullName + "." + field.Name).Remove(0, typeof(ErrorCodes).FullName!.Length + 1).Replace("+", ".", StringComparison.OrdinalIgnoreCase);
                    int value = (int)field.GetRawConstantValue()!;
                    errorCodes.Add(name, value);
                }

                foreach (var nestedType in type.GetNestedTypes())
                {
                    RecursiveCheckErrorCode(nestedType);
                }
            }

            RecursiveCheckErrorCode(typeof(ErrorCodes));

            return errorCodes;
        }

        public void Process(DocumentProcessorContext context)
        {
            StringBuilder description = new StringBuilder();
            description.AppendLine("# Error Codes");
            description.AppendLine("name | value");
            description.AppendLine("---- | -----");
            foreach (var (name, value) in GetAllErrorCodes())
            {
                description.AppendLine($"`{name}` | `{value}`");
            }

            context.Document.Info.Description = description.ToString();
        }
    }
}