1+ using System ;
2+ using System . Collections . Generic ;
3+ using System . Reflection ;
4+ using System . Threading . Tasks ;
5+ using Microsoft . AspNetCore . Http ;
6+ using Simplify . Web . Controllers . Execution ;
7+ using Simplify . Web . Controllers . Meta ;
8+ using Simplify . Web . Controllers . V2 . Metadata ;
9+
10+ namespace Simplify . Web . Controllers . V2 . Execution ;
11+
12+ /// <summary>
13+ /// Provides v2 controller executor.
14+ /// </summary>
15+ /// <param name="controllerFactory">The v2 controller factory.</param>
16+ public class Controller2Executor ( IController2Factory controllerFactory ) : IControllerExecutor
17+ {
18+ public bool CanHandle ( IControllerMetadata controllerMetadata ) => controllerMetadata is IController2Metadata ;
19+
20+ public Task < ControllerResponse ? > ExecuteAsync ( IMatchedController matchedController , HttpContext context )
21+ {
22+ var controllerMetadata = ( IController2Metadata ) matchedController . Controller ;
23+ var controller = controllerFactory . CreateController ( matchedController ) ;
24+ var methodParams = ConstructMethodParams ( controllerMetadata . InvokeMethodParameters , matchedController . RouteParameters ! ) ;
25+
26+ return InvokeAsync ( controllerMetadata . InvokeMethodInfo , methodParams , controller ) ;
27+ }
28+
29+ private static async Task < ControllerResponse ? > InvokeAsync ( MethodInfo methodInfo , IList < object > methodParams ,
30+ ResponseShortcutsControllerBase controller )
31+ {
32+ var result = methodInfo . Invoke ( controller , [ .. methodParams ] ) ;
33+
34+ switch ( result )
35+ {
36+ case ControllerResponse response :
37+ return response ;
38+
39+ case Task < ControllerResponse > response :
40+ await response ;
41+ return response . Result ;
42+
43+ case Task task :
44+ await task ;
45+ break ;
46+ }
47+
48+ return null ;
49+ }
50+
51+ private static IList < object > ConstructMethodParams ( IDictionary < string , Type > invokeMethodParameters , IReadOnlyDictionary < string , object > routeParameters )
52+ {
53+ var result = new List < object > ( invokeMethodParameters . Count ) ;
54+
55+ foreach ( var item in invokeMethodParameters . Keys )
56+ {
57+ if ( ! routeParameters . TryGetValue ( item , out var parameter ) )
58+ throw new InvalidOperationException ( $ "Route parameter with the name '{ item } ' is not found.") ;
59+
60+ result . Add ( parameter ) ;
61+ }
62+
63+ return result ;
64+ }
65+ }
0 commit comments