Repository navigation
Expand file tree
/
Copy pathSwaggerApiService.cs
More file actions
450 lines (397 loc) · 17 KB
/
Copy pathSwaggerApiService.cs
File metadata and controls
450 lines (397 loc) · 17 KB
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using ServiceStack.Host;
using ServiceStack.Text;
using ServiceStack.Web;
namespace ServiceStack.Api.Swagger
{
[DataContract]
public class ResourceRequest
{
[DataMember(Name = "apiKey")]
public string ApiKey { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
}
[DataContract]
public class ResourceResponse
{
[DataMember(Name = "apiVersion")]
public string ApiVersion { get; set; }
[DataMember(Name = "basePath")]
public string BasePath { get; set; }
[DataMember(Name = "resourcePath")]
public string ResourcePath { get; set; }
[DataMember(Name = "apis")]
public List<MethodDescription> Apis { get; set; }
[DataMember(Name = "models")]
public Dictionary<string, SwaggerModel> Models { get; set; }
}
[DataContract]
public class SwaggerModel
{
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "properties")]
public Dictionary<string, ModelProperty> Properties { get; set; }
}
[DataContract]
public class MethodDescription
{
[DataMember(Name = "path")]
public string Path { get; set; }
[DataMember(Name = "description")]
public string Description { get; set; }
[DataMember(Name = "operations")]
public List<MethodOperation> Operations { get; set; }
}
[DataContract]
public class MethodOperation
{
[DataMember(Name = "httpMethod")]
public string HttpMethod { get; set; }
[DataMember(Name = "nickname")]
public string Nickname { get; set; }
[DataMember(Name = "summary")]
public string Summary { get; set; }
[DataMember(Name = "notes")]
public string Notes { get; set; }
[DataMember(Name = "parameters")]
public List<MethodOperationParameter> Parameters { get; set; }
[DataMember(Name = "responseClass")]
public string ResponseClass { get; set; }
[DataMember(Name = "errorResponses")]
public List<ErrorResponseStatus> ErrorResponses { get; set; }
}
[DataContract]
public class ErrorResponseStatus
{
[DataMember(Name = "code")]
public int StatusCode { get; set; }
[DataMember(Name = "reason")]
public string Reason { get; set; }
}
[DataContract]
public class ModelProperty
{
[DataMember(Name = "description")]
public string Description { get; set; }
[DataMember(Name = "type")]
public string Type { get; set; }
[DataMember(Name = "items")]
public Dictionary<string, string> Items { get; set; }
[DataMember(Name = "allowableValues")]
public ParameterAllowableValues AllowableValues { get; set; }
[DataMember(Name = "required")]
public bool Required { get; set; }
}
[DataContract]
public class MethodOperationParameter
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "description")]
public string Description { get; set; }
[DataMember(Name = "paramType")]
public string ParamType { get; set; }
[DataMember(Name = "allowMultiple")]
public bool AllowMultiple { get; set; }
[DataMember(Name = "required")]
public bool Required { get; set; }
[DataMember(Name = "dataType")]
public string DataType { get; set; }
[DataMember(Name = "allowableValues")]
public ParameterAllowableValues AllowableValues { get; set; }
}
[DataContract]
public class ParameterAllowableValues
{
[DataMember(Name = "valueType")]
public string ValueType { get; set; }
[DataMember(Name = "values")]
public string[] Values { get; set; }
[DataMember(Name = "min")]
public int? Min { get; set; }
[DataMember(Name = "max")]
public int? Max { get; set; }
}
[DefaultRequest(typeof(ResourceRequest))]
public class SwaggerApiService : Service
{
internal static bool UseCamelCaseModelPropertyNames { get; set; }
internal static bool UseLowercaseUnderscoreModelPropertyNames { get; set; }
internal static bool DisableAutoDtoInBodyParam { get; set; }
private readonly Regex nicknameCleanerRegex = new Regex(@"[\{\}\*\-_/]*", RegexOptions.Compiled);
public object Get(ResourceRequest request)
{
var httpReq = RequestContext.Get<IHttpRequest>();
var path = "/" + request.Name;
var map = HostContext.ServiceController.RestPathMap;
var paths = new List<RestPath>();
var basePath = HostContext.Config.WebHostUrl;
if (basePath == null)
{
basePath = HostContext.Config.UseHttpsLinks
? httpReq.GetParentPathUrl().ToHttps()
: httpReq.GetParentPathUrl();
}
if (basePath.EndsWith(SwaggerResourcesService.RESOURCE_PATH, StringComparison.OrdinalIgnoreCase))
{
basePath = basePath.Substring(0, basePath.LastIndexOf(SwaggerResourcesService.RESOURCE_PATH, StringComparison.OrdinalIgnoreCase));
}
var meta = HostContext.Metadata;
foreach (var key in map.Keys)
{
paths.AddRange(map[key].Where(x => (x.Path == path || x.Path.StartsWith(path + "/") && meta.IsVisible(Request, Format.Json, x.RequestType.Name))));
}
var models = new Dictionary<string, SwaggerModel>();
foreach (var restPath in paths)
{
ParseModel(models, restPath.RequestType);
}
return new ResourceResponse
{
ResourcePath = path,
BasePath = basePath,
Apis = new List<MethodDescription>(paths.Select(p => FormateMethodDescription(p, models)).ToArray().OrderBy(md => md.Path)),
Models = models
};
}
private static readonly Dictionary<Type, string> ClrTypesToSwaggerScalarTypes = new Dictionary<Type, string> {
{typeof(byte), SwaggerType.Byte},
{typeof(sbyte), SwaggerType.Byte},
{typeof(bool), SwaggerType.Boolean},
{typeof(short), SwaggerType.Int},
{typeof(ushort), SwaggerType.Int},
{typeof(int), SwaggerType.Int},
{typeof(uint), SwaggerType.Int},
{typeof(long), SwaggerType.Long},
{typeof(ulong), SwaggerType.Long},
{typeof(float), SwaggerType.Float},
{typeof(double), SwaggerType.Double},
{typeof(decimal), SwaggerType.Double},
{typeof(string), SwaggerType.String},
{typeof(DateTime), SwaggerType.Date}
};
private static bool IsSwaggerScalarType(Type type)
{
return ClrTypesToSwaggerScalarTypes.ContainsKey(type) || type.IsEnum;
}
private static string GetSwaggerTypeName(Type type)
{
var lookupType = Nullable.GetUnderlyingType(type) ?? type;
return ClrTypesToSwaggerScalarTypes.ContainsKey(lookupType)
? ClrTypesToSwaggerScalarTypes[lookupType]
: lookupType.Name;
}
private static Type GetListElementType(Type type)
{
if (type.IsArray) return type.GetElementType();
if (!type.IsGenericType) return null;
var genericType = type.GetGenericTypeDefinition();
if (genericType == typeof(List<>) || genericType == typeof(IList<>) || genericType == typeof(IEnumerable<>))
return type.GetGenericArguments()[0];
return null;
}
private static bool IsListType(Type type)
{
return GetListElementType(type) != null;
}
private static bool IsNullable(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
private static void ParseModel(IDictionary<string, SwaggerModel> models, Type modelType)
{
if (IsSwaggerScalarType(modelType)) return;
var modelId = modelType.Name;
if (models.ContainsKey(modelId)) return;
var model = new SwaggerModel
{
Id = modelId,
Properties = new Dictionary<string, ModelProperty>()
};
models[model.Id] = model;
foreach (var prop in modelType.GetProperties())
{
var allApiDocAttributes = prop
.AllAttributes<ApiMemberAttribute>()
.Where(attr => prop.Name.Equals(attr.Name, StringComparison.InvariantCultureIgnoreCase))
.ToList();
var apiDoc = allApiDocAttributes.FirstOrDefault(attr => attr.ParameterType == "body");
if (allApiDocAttributes.Any() && apiDoc == null) continue;
var propertyType = prop.PropertyType;
var modelProp = new ModelProperty { Type = GetSwaggerTypeName(propertyType), Required = !IsNullable(propertyType) };
if (IsListType(propertyType))
{
modelProp.Type = SwaggerType.Array;
var listItemType = GetListElementType(propertyType);
modelProp.Items = new Dictionary<string, string> {
{ IsSwaggerScalarType(listItemType) ? "type" : "$ref", GetSwaggerTypeName(listItemType) }
};
ParseModel(models, listItemType);
}
else if (propertyType.IsEnum)
{
modelProp.Type = SwaggerType.String;
modelProp.AllowableValues = new ParameterAllowableValues
{
Values = Enum.GetNames(propertyType),
ValueType = "LIST"
};
}
else
{
ParseModel(models, propertyType);
}
var descriptionAttr = prop.FirstAttribute<DescriptionAttribute>();
if (descriptionAttr != null)
modelProp.Description = descriptionAttr.Description;
if (apiDoc != null)
modelProp.Description = apiDoc.Description;
var allowableValues = prop.FirstAttribute<ApiAllowableValuesAttribute>();
if (allowableValues != null)
modelProp.AllowableValues = GetAllowableValue(allowableValues);
model.Properties[GetModelPropertyName(prop)] = modelProp;
}
}
private static string GetModelPropertyName(PropertyInfo prop)
{
return UseCamelCaseModelPropertyNames
? (UseLowercaseUnderscoreModelPropertyNames ? prop.Name.ToLowercaseUnderscore() : prop.Name.ToCamelCase())
: prop.Name;
}
private static string GetResponseClass(IRestPath restPath, IDictionary<string, SwaggerModel> models)
{
// Given: class MyDto : IReturn<X>. Determine the type X.
foreach (var i in restPath.RequestType.GetInterfaces())
{
if (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IReturn<>))
{
var returnType = i.GetGenericArguments()[0];
// Handle IReturn<List<SomeClass>> or IReturn<SomeClass[]>
if (IsListType(returnType))
{
var listItemType = GetListElementType(returnType);
ParseModel(models, listItemType);
return string.Format("List[{0}]", GetSwaggerTypeName(listItemType));
}
ParseModel(models, returnType);
return GetSwaggerTypeName(i.GetGenericArguments()[0]);
}
}
return null;
}
private static List<ErrorResponseStatus> GetMethodResponseCodes(Type requestType)
{
return requestType
.AllAttributes<IApiResponseDescription>()
.Select(x => new ErrorResponseStatus
{
StatusCode = x.StatusCode,
Reason = x.Description
}).ToList();
}
private MethodDescription FormateMethodDescription(RestPath restPath, Dictionary<string, SwaggerModel> models)
{
var verbs = new List<string>();
var summary = restPath.Summary;
var notes = restPath.Notes;
if (restPath.AllowsAllVerbs)
{
verbs.AddRange(new[] { "GET", "POST", "PUT", "DELETE" });
}
else
verbs.AddRange(restPath.AllowedVerbs.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries));
var nickName = nicknameCleanerRegex.Replace(restPath.Path, "");
var md = new MethodDescription
{
Path = restPath.Path,
Description = summary,
Operations = verbs.Select(verb =>
new MethodOperation
{
HttpMethod = verb,
Nickname = verb.ToLowerInvariant() + nickName,
Summary = summary,
Notes = notes,
Parameters = ParseParameters(verb, restPath.RequestType, models),
ResponseClass = GetResponseClass(restPath, models),
ErrorResponses = GetMethodResponseCodes(restPath.RequestType)
}).ToList()
};
return md;
}
private static ParameterAllowableValues GetAllowableValue(ApiAllowableValuesAttribute attr)
{
if (attr != null)
{
return new ParameterAllowableValues()
{
ValueType = attr.Type,
Values = attr.Values,
Max = attr.Max,
Min = attr.Min
};
}
return null;
}
private static List<MethodOperationParameter> ParseParameters(string verb, Type operationType, IDictionary<string, SwaggerModel> models)
{
var hasDataContract = operationType.HasAttribute<DataContractAttribute>();
var properties = operationType.GetProperties();
var paramAttrs = new Dictionary<string, ApiMemberAttribute[]>();
var allowableParams = new List<ApiAllowableValuesAttribute>();
foreach (var property in properties)
{
var propertyName = property.Name;
if (hasDataContract)
{
var dataMemberAttr = property.FirstAttribute<DataMemberAttribute>();
if (dataMemberAttr != null && dataMemberAttr.Name != null)
{
propertyName = dataMemberAttr.Name;
}
}
paramAttrs[propertyName] = property.AllAttributes<ApiMemberAttribute>();
allowableParams.AddRange(property.AllAttributes<ApiAllowableValuesAttribute>());
}
var methodOperationParameters = new List<MethodOperationParameter>();
foreach (var key in paramAttrs.Keys)
{
var value = paramAttrs[key];
methodOperationParameters.AddRange(
from ApiMemberAttribute member in value
where member.Verb == null || string.Compare(member.Verb, verb, StringComparison.InvariantCultureIgnoreCase) == 0
select new MethodOperationParameter
{
DataType = member.DataType,
AllowMultiple = member.AllowMultiple,
Description = member.Description,
Name = member.Name ?? key,
ParamType = member.ParameterType,
Required = member.IsRequired,
AllowableValues = GetAllowableValue(allowableParams.FirstOrDefault(attr => attr.Name == member.Name))
});
}
if (!DisableAutoDtoInBodyParam)
{
if (!HttpMethods.Get.Equals(verb, StringComparison.OrdinalIgnoreCase) && !methodOperationParameters.Any(p => p.ParamType.Equals("body", StringComparison.OrdinalIgnoreCase)))
{
ParseModel(models, operationType);
methodOperationParameters.Add(new MethodOperationParameter()
{
DataType = GetSwaggerTypeName(operationType),
ParamType = "body"
});
}
}
return methodOperationParameters;
}
}
}