-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathActionFunctions.Url.cs
171 lines (150 loc) · 7.65 KB
/
ActionFunctions.Url.cs
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace NTypewriter.CodeModel.Functions
{
/// <summary>
/// Set of functions that operates on IMethod
/// </summary>
public static partial class ActionFunctions
{
/// <summary>
/// Returns the url for the Web API action based on route attributes (or the supplied convention route if no attributes are present).
/// Route parameters are converted to TypeScript string interpolation syntax by prefixing all parameters with $ e.g. ${id}.
/// Optional parameters are added as QueryString parameters for GET and HEAD requests.
/// </summary>
public static string Url(this IMethod method)
{
var prefix = GetRouteFromTypeAttributes(method.ContainingType);
var postfix = GetRouteFromMethodAttributes(method);
string route = null;
if (postfix?.StartsWith("~/") == true)
{
route = postfix.Substring(2);
}
if (postfix?.StartsWith("/") == true)
{
route = postfix.Substring(1);
}
if (route == null)
{
route = $"{prefix?.Trim('/')}/{postfix}".Trim('/');
}
route = ReplaceSpecialParameters(method, route);
route = ConvertRouteParameters(route);
route = AppendQueryString(method, route);
route = AppendFromQuery(method, route);
return route;
}
private static string GetRouteFromTypeAttributes(IType type)
{
var routeAttribute = type.Attributes.FirstOrDefault(a => a.Name == "RoutePrefix" || a.Name == "Route");
var route = routeAttribute?.Arguments.Where(x => x.Name == "template" || x.Name == "prefix").Select(x => x.Value.ToString()).FirstOrDefault();
if (String.IsNullOrEmpty(route) && type.BaseType != null)
{
route = GetRouteFromTypeAttributes(type.BaseType);
}
return route;
}
private static string GetRouteFromMethodAttributes(IMethod method)
{
var routeAttributes = method.Attributes.Where(a => a.Name == "Route" || a.Name.StartsWith("Http"));
var route = routeAttributes.SelectMany(x => x.Arguments).Where(x => x.Name == "template").Select(x => x.Value).Where(x => x != null).FirstOrDefault()?.ToString();
return route;
}
private static string ReplaceSpecialParameters(IMethod method, string route)
{
string controllerName = method.ContainingType.BareName;
controllerName = controllerName.EndsWith("Controller") ? controllerName.Substring(0, controllerName.Length - "Controller".Length) : controllerName;
route = route.Replace("{controller}", controllerName).Replace("[controller]", controllerName);
var action = method.Attributes.FirstOrDefault(a => a.Name == "ActionName")?.Arguments.FirstOrDefault(x => x.Name == "name")?.Value.ToString();
string actionName = action ?? method.BareName;
route = route.Replace("{action}", actionName).Replace("[action]", actionName);
return route;
}
private static readonly Regex RouteParameterRegex = new Regex(@"\{(\w+).*?\}", RegexOptions.Singleline | RegexOptions.Compiled);
private static string ConvertRouteParameters(string route)
{
return RouteParameterRegex.Replace(route, m => $"${{{m.Groups[1].Value}}}");
}
private static string AppendQueryString(IMethod method, string route)
{
var parameterAttributeBlackList = new[] { "FromHeader", "FromBody", "FromRoute", "FromServices" };
var queryParameters = new List<string>();
foreach (var parameter in method.Parameters.Where(p => p.Type.IsSimple() && p.Attributes.All(x => !parameterAttributeBlackList.Contains(x.Name))))
{
if (!route.Contains($"${{{parameter.BareName}}}"))
{
if (parameter.Type.Name == "string")
{
queryParameters.Add($"{parameter.BareName}=${{encodeURIComponent({parameter.BareName})}}");
}
else
{
queryParameters.Add($"{parameter.BareName}=${{{parameter.BareName}}}");
}
}
}
if (queryParameters.Any())
{
var prefix = route.Contains("?") ? "&" : "?";
route += $"{prefix}{String.Join("&", queryParameters)}";
}
return route;
}
private static string AppendFromQuery(IMethod method, string route)
{
string connector = route.Contains("?") ? "&" : "?";
var builder = new StringBuilder();
foreach (IParameter parameter in method.Parameters)
{
if ((!parameter.Type.IsSimple()) && parameter.Attributes.Any(x => x.Name == "FromQuery"))
{
if (parameter.Type is IClass @class)
{
foreach (var prop in @class.Properties)
{
string urlParam = prop.BareName.ToLowerFirst();
string memberAccessOperator = IsNullable(parameter) ? "?." : ".";
string propertyAccess = string.Concat(parameter.BareName, memberAccessOperator, prop.BareName.ToLowerFirst());
builder.Append(connector);
if (prop.Type.IsEnumerable && !prop.Type.IsSimple())
{
string itemValue = GetEnumerableType(prop.Type)?.Name == "string" ? "${encodeURIComponent(item)}" : "${item}";
builder.Append($"${{{propertyAccess}{(prop.Type.IsNullable ? "?." : ".")}map(item => `{urlParam}={itemValue}`).join('&')}}");
}
else
{
string urlValue = parameter.Type.Name == "string" ? $"${{encodeURIComponent({propertyAccess})}}" : $"${{{propertyAccess}}}";
builder.Append($"{urlParam}={urlValue}");
}
connector = "&";
}
}
else if (parameter.Type.IsEnumerable)
{
string urlParam = parameter.BareName.ToLowerFirst();
string memberAccessOperator = IsNullable(parameter) ? "?." : ".";
string itemValue = GetEnumerableType(parameter.Type)?.Name == "string" ? "${encodeURIComponent(item)}" : "${item}";
builder.Append(connector).Append($"${{{parameter.BareName}{memberAccessOperator}map(item => `{urlParam}={itemValue}`).join('&')}}");
connector = "&";
}
}
}
var postfix = builder.ToString();
return route + postfix;
}
private static IType GetEnumerableType(IType enumerableType)
{
if (!enumerableType.IsEnumerable)
return null;
return enumerableType.ArrayType ?? enumerableType.TypeArguments.FirstOrDefault();
}
private static bool IsNullable(IParameter parameter)
{
return parameter.Type.IsNullable || (parameter.HasDefaultValue && parameter.DefaultValue == null);
}
}
}