1+ using NJsonSchema ;
2+ using NJsonSchema . Generation ;
3+ using SOFTURE . Language . Common ;
4+
5+ namespace SOFTURE . Common . StronglyTypedIdentifiers . API . SchemaProcessors ;
6+
7+ public sealed class StronglyTypedIdSchemaProcessor : ISchemaProcessor
8+ {
9+ private static readonly Type IdentifierBaseGenericType = typeof ( IdentifierBase < > ) ;
10+
11+ private const string UuidFormat = "uuid" ;
12+ private const string Int32Format = "int32" ;
13+ private const string Int64Format = "int64" ;
14+
15+ public void Process ( SchemaProcessorContext context )
16+ {
17+ var type = context . ContextualType . Type ;
18+
19+ if ( ! IsStronglyTypedId ( type ) )
20+ return ;
21+
22+ var underlyingType = GetUnderlyingType ( type ) ;
23+ if ( underlyingType == null )
24+ return ;
25+
26+ var schema = CreateSchemaForUnderlyingType ( underlyingType ) ;
27+ context . Schema . Type = schema . Type ;
28+ context . Schema . Format = schema . Format ;
29+ context . Schema . Properties . Clear ( ) ;
30+ context . Schema . AllOf . Clear ( ) ;
31+ context . Schema . AnyOf . Clear ( ) ;
32+ context . Schema . OneOf . Clear ( ) ;
33+ }
34+
35+ private static bool IsStronglyTypedId ( Type type )
36+ {
37+ if ( type . IsInterface || type . IsAbstract )
38+ return false ;
39+
40+ var baseType = type . BaseType ;
41+ while ( baseType != null )
42+ {
43+ if ( baseType . IsGenericType )
44+ {
45+ var genericTypeDef = baseType . GetGenericTypeDefinition ( ) ;
46+ if ( genericTypeDef == IdentifierBaseGenericType )
47+ {
48+ return true ;
49+ }
50+ }
51+ baseType = baseType . BaseType ;
52+ }
53+
54+ return typeof ( IIdentifier ) . IsAssignableFrom ( type ) ;
55+ }
56+
57+ private static Type ? GetUnderlyingType ( Type stronglyTypedIdType )
58+ {
59+ var baseType = stronglyTypedIdType . BaseType ;
60+ while ( baseType != null )
61+ {
62+ if ( baseType . IsGenericType )
63+ {
64+ var args = baseType . GetGenericArguments ( ) ;
65+ if ( args . Length > 0 )
66+ return args [ 0 ] ;
67+ }
68+ baseType = baseType . BaseType ;
69+ }
70+ return null ;
71+ }
72+
73+ private static JsonSchema CreateSchemaForUnderlyingType ( Type underlyingType )
74+ {
75+ if ( underlyingType == typeof ( Guid ) )
76+ {
77+ return new JsonSchema
78+ {
79+ Type = JsonObjectType . String ,
80+ Format = UuidFormat
81+ } ;
82+ }
83+
84+ if ( underlyingType == typeof ( int ) )
85+ {
86+ return new JsonSchema
87+ {
88+ Type = JsonObjectType . Integer ,
89+ Format = Int32Format
90+ } ;
91+ }
92+
93+ if ( underlyingType == typeof ( long ) )
94+ {
95+ return new JsonSchema
96+ {
97+ Type = JsonObjectType . Integer ,
98+ Format = Int64Format
99+ } ;
100+ }
101+
102+ return new JsonSchema
103+ {
104+ Type = JsonObjectType . String
105+ } ;
106+ }
107+ }
0 commit comments