1
+ using System ;
2
+ using System . Collections . Generic ;
3
+ using System . Linq ;
4
+ using System . Text . Encodings . Web ;
5
+ using System . Text . Json ;
6
+ using Simplify . Web . Meta ;
7
+ using Simplify . Web . Postman . Models ;
8
+
9
+ namespace Simplify . Web . Postman . PartBuilders
10
+ {
11
+ /// <summary>
12
+ /// Provides request builder
13
+ /// </summary>
14
+ public static class RequestBuilder
15
+ {
16
+ /// <summary>
17
+ /// The base URL path.
18
+ /// </summary>
19
+ public const string DefaultBaseUrlPath = "{{BaseUrl}}" ;
20
+
21
+ private static string ? _baseUrlPath ;
22
+
23
+ /// <summary>
24
+ /// Gets or sets the base URL path.
25
+ /// </summary>
26
+ public static string BaseUrlPath
27
+ {
28
+ get => _baseUrlPath ?? DefaultBaseUrlPath ;
29
+ set => _baseUrlPath = value ?? throw new NotImplementedException ( nameof ( value ) ) ;
30
+ }
31
+
32
+ /// <summary>
33
+ /// Builds the request
34
+ /// </summary>
35
+ /// <param name="metaData">The meta data.</param>
36
+ /// <param name="route">The route.</param>
37
+ public static Request Build ( IControllerMetaData metaData , KeyValuePair < HttpMethod , string > route ) =>
38
+ new ( )
39
+ {
40
+ Url = new Url
41
+ {
42
+ Host = BaseUrlPath ,
43
+ Path = BuildPath ( route . Value )
44
+ } ,
45
+ Method = route . Key . ToString ( ) . ToUpper ( ) ,
46
+ Body = TryBuildBody ( metaData )
47
+ } ;
48
+
49
+ private static IList < string > BuildPath ( string controllerRoute ) => controllerRoute . Split ( new [ ] { '/' } , StringSplitOptions . RemoveEmptyEntries ) . ToList ( ) ;
50
+
51
+ private static Body ? TryBuildBody ( IControllerMetaData metaData )
52
+ {
53
+ if ( metaData . ControllerType . BaseType . GenericTypeArguments . Length == 0 )
54
+ return null ;
55
+
56
+ var body = new Body ( )
57
+ {
58
+ Mode = "raw" ,
59
+ Raw = BuildRequestJsonData ( metaData . ControllerType . BaseType . GenericTypeArguments [ 0 ] ) ,
60
+ Options = new ( )
61
+ {
62
+ Raw = new ( )
63
+ {
64
+ Language = "json"
65
+ }
66
+ }
67
+ } ;
68
+
69
+ return body ;
70
+ }
71
+ private static string BuildRequestJsonData ( Type modelType ) => JsonSerializer . Serialize ( Activator . CreateInstance ( modelType ) , new ( )
72
+ {
73
+ WriteIndented = true
74
+ } ) ;
75
+ }
76
+ }
0 commit comments